BZOJ1021 SHOI2008循环的债务
dp模拟即可。
d[i][j][k]表示使用前i种面值,1号手里钱为j,2号手里钱为k时最少操作数
使用滚动数组压缩空间
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int n = 6; const int M = 1005; const int val[n] = {1, 5, 10, 20, 50, 100}; int x1, x2, x3; int now, tot; int suma, sumb, dis; int sum[3], Cnt[n]; int d[2][M][M], cnt[3][n]; int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } inline void update(int &x, int y){ if (x == -1) x = y; else x = min(x, y); } inline int calc(int i,int a,int b){ return (abs(a - cnt[0][i]) + abs(b - cnt[1][i]) + abs(Cnt[i] - a - b - cnt[2][i])) / 2; } int main(){ scanf("%d%d%d", &x1, &x2, &x3); for (int i = 0; i < 3; ++i){ sum[i] = 0; for (int j = n - 1; j >= 0; --j){ scanf("%d", cnt[i] + j); Cnt[j] += cnt[i][j]; sum[i] += cnt[i][j] * val[j]; } tot += sum[i]; } int ea = sum[0], eb = sum[1], ec = sum[2]; ea += x3 - x1, eb += x1 - x2, ec += x2 - x3; if (ea < 0 || eb < 0 || ec < 0 || ea + eb + ec != tot) {printf("impossible\n");return 0;} memset(d[0], -1, sizeof(d[0])); d[0][sum[0]][sum[1]] = 0; for (int i = 0; i < n; ++i) { now = i & 1; int g=val[i]; for(int j=i+1;j<n;++j) g=gcd(g,val[j]); memset(d[now ^ 1], -1, sizeof(d[now ^ 1])); for (int j = 0; j <= tot; ++j) { for (int k = 0; j + k <= tot; ++k) { if (d[now][j][k] >= 0) { update(d[now ^ 1][j][k], d[now][j][k]); for (int a = 0; a <= Cnt[i]; ++a) { for (int b = 0; a + b <= Cnt[i]; ++b) { suma = j + val[i] * (a - cnt[0][i]); sumb = k + val[i] * (b - cnt[1][i]); if (suma >= 0 && sumb >= 0 && suma + sumb <= tot) { dis = calc(i,a,b); update(d[now ^ 1][suma][sumb], d[now][j][k] + dis); } } } } } } } if(d[n&1][ea][eb]<0) puts("impossible"); else printf("%d\n", d[n & 1][ea][eb]); return 0; }
生命中真正重要的不是你遭遇了什么,而是你记住了哪些事,又是如何铭记的。