BZOJ1021 SHOI2008循环的债务

时间:2023-03-09 05:58:57
BZOJ1021 SHOI2008循环的债务

dp模拟即可。

d[i][j][k]表示使用前i种面值,1号手里钱为j,2号手里钱为k时最少操作数

使用滚动数组压缩空间

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int n = ;
const int M = ;
const int val[n] = {, , , , , };
int x1, x2, x3;
int now, tot;
int suma, sumb, dis;
int sum[], Cnt[n];
int d[][M][M], cnt[][n];
int gcd(int a,int b)
{
return b==?a:gcd(b,a%b);
}
inline void update(int &x, int y){
if (x == -) x = y;
else x = min(x, y);
} inline int calc(int i,int a,int b){
return (abs(a - cnt[][i]) + abs(b - cnt[][i]) + abs(Cnt[i] - a - b - cnt[][i])) / ;
} int main(){
scanf("%d%d%d", &x1, &x2, &x3);
for (int i = ; i < ; ++i){
sum[i] = ;
for (int j = n - ; j >= ; --j){
scanf("%d", cnt[i] + j);
Cnt[j] += cnt[i][j];
sum[i] += cnt[i][j] * val[j];
}
tot += sum[i];
}
int ea = sum[], eb = sum[], ec = sum[];
ea += x3 - x1, eb += x1 - x2, ec += x2 - x3;
if (ea < || eb < || ec < || ea + eb + ec != tot)
{printf("impossible\n");return ;}
memset(d[], -, sizeof(d[]));
d[][sum[]][sum[]] = ;
for (int i = ; i < n; ++i)
{
now = i & ;
int g=val[i];
for(int j=i+;j<n;++j)
g=gcd(g,val[j]);
memset(d[now ^ ], -, sizeof(d[now ^ ]));
for (int j = ; j <= tot; ++j)
{
for (int k = ; j + k <= tot; ++k)
{
if (d[now][j][k] >= )
{
update(d[now ^ ][j][k], d[now][j][k]);
for (int a = ; a <= Cnt[i]; ++a)
{
for (int b = ; a + b <= Cnt[i]; ++b)
{
suma = j + val[i] * (a - cnt[][i]);
sumb = k + val[i] * (b - cnt[][i]);
if (suma >= && sumb >= && suma + sumb <= tot)
{
dis = calc(i,a,b);
update(d[now ^ ][suma][sumb], d[now][j][k] + dis);
}
}
}
}
}
}
}
if(d[n&][ea][eb]<) puts("impossible");
else printf("%d\n", d[n & ][ea][eb]);
return ;
}