USACO shopping
完全背包多增加了几维而已, 直接贴代码:
/* ID: m1500293 LANG: C++ PROG: shopping */ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int s; struct FangAn { int num[5]; //商品的数量 int cost; //方案的话费 FangAn() {} FangAn(int a[], int ct) { for(int i=0; i<5; i++) num[i] = a[i]; cost = ct; } }fang[110]; int numhash[1010], hao; int getnum(int n) { if(numhash[n] == -1) numhash[n] = hao++; return numhash[n]; } int value[10]; //商品单价 int num[10]; //需要购买的商品的数量 int f[102][7][7][7][7][7]; int judge(int a[], int s) { for(int i=0; i<5; i++) { if(a[i] < fang[s].num[i]) return false; } return true; } int main() { freopen("shopping.in", "r", stdin); freopen("shopping.out", "w", stdout); memset(numhash, -1, sizeof(numhash)); hao = 0; scanf("%d", &s); for(int i=1; i<=s; i++) { int n; scanf("%d", &n); int a[5]; memset(a, 0, sizeof(a)); for(int j=0; j<n; j++) { int c, k; //k个编号为c的商品 scanf("%d%d", &c, &k); a[getnum(c)] = k; } int cost; scanf("%d", &cost); fang[i] = FangAn(a, cost); } memset(num, 0, sizeof(num)); memset(value, 0, sizeof(value)); int b; scanf("%d", &b); for(int i=0; i<b; i++) { int c, k, v; scanf("%d%d%d", &c, &k, &v); num[getnum(c)] = k; value[getnum(c)] = v; } memset(f, 0x3f, sizeof(f)); int a[5]; for(a[0]=0; a[0]<=5; a[0]++) for(a[1]=0; a[1]<=5; a[1]++) for(a[2]=0; a[2]<=5; a[2]++) for(a[3]=0; a[3]<=5; a[3]++) for(a[4]=0; a[4]<=5; a[4]++) { int sum = 0; for(int i=0; i<5; i++) sum += value[i]*a[i]; f[0][a[0]][a[1]][a[2]][a[3]][a[4]] = sum; } for(int i=1; i<=s; i++) { for(a[0]=0; a[0]<=5; a[0]++) for(a[1]=0; a[1]<=5; a[1]++) for(a[2]=0; a[2]<=5; a[2]++) for(a[3]=0; a[3]<=5; a[3]++) for(a[4]=0; a[4]<=5; a[4]++) { int &tp = f[i][a[0]][a[1]][a[2]][a[3]][a[4]]; if(judge(a, i)) { int tp2 = f[i][a[0]-fang[i].num[0]][a[1]-fang[i].num[1]][a[2]-fang[i].num[2]][a[3]-fang[i].num[3]][a[4]-fang[i].num[4]]; int tp3 = f[i-1][a[0]][a[1]][a[2]][a[3]][a[4]]; tp = min(tp, min(tp3, tp2+fang[i].cost)); } else tp = min(tp, f[i-1][a[0]][a[1]][a[2]][a[3]][a[4]]); } } printf("%d\n", f[s][num[0]][num[1]][num[2]][num[3]][num[4]]); return 0; }