https://www.nowcoder.com/acm/contest/141#question
一眼背包,用四维dp记录在A,B,C,D条件限制下可以获得的最大知识点,但是题目要求输出路径,在输入中包含0这样的样例,原本的递归寻找路径变的不可行,就需要开五维dp记录在i组条件下ABCD的最大知识点,空间复杂度为36 ^ 5,测试可以通过,但本题有更加优秀的解法,就是在原本四维dp的条件下同时用状压记录已经选择的物品,输出的时候只要输出加入状压的物品即可。
#include <map> #include <set> #include <cmath> #include <queue> #include <stack> #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <iostream> #include <algorithm> #include <functional> #define For(i, x, y) for(int i=x; i<=y; i++) #define _For(i, x, y) for(int i=x; i>=y; i--) #define Mem(f, x) memset(f, x, sizeof(f)) #define Sca(x) scanf("%d", &x) #define Scl(x) scanf("%lld",&x); #define Pri(x) printf("%d ", x) #define Prl(x) printf("%lld ",x); #define CLR(u) for(int i = 0; i <= N ; i ++) u[i].clear(); #define LL long long #define ULL unsigned long long #define mp make_pair #define PII pair<int,int> #define PIL pair<int,long long> #define PLL pair<long long,long long> #define pb push_back #define fi first #define se second using namespace std; typedef vector<int> VI; const double eps = 1e-9; const int maxn = 40; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; inline int read() { int now=0;register char c=getchar(); for(;!isdigit(c);c=getchar()); for(;isdigit(c);now=now*10+c-'0',c=getchar()); return now; } int N,M; struct DP{ ULL c; int num; }dp[maxn][maxn][maxn][maxn];; struct group{ int a,b,c,d,p; }G[maxn]; int A,B,C,D; VI P; int main() { N = read(); For(i,1,N){ G[i].a = read(); G[i].b = read(); G[i].c = read(); G[i].d = read(); Sca(G[i].p); } A = read(); B = read(); C = read(); D = read(); Mem(dp,0); For(i,1,N){ _For(a,A ,G[i].a){ _For(b,B,G[i].b){ _For(c,C,G[i].c){ _For(d,D,G[i].d){ if(dp[a][b][c][d].num < dp[a - G[i].a][b - G[i].b][c - G[i].c][d - G[i].d].num + G[i].p){ dp[a][b][c][d].num = dp[a - G[i].a][b - G[i].b][c - G[i].c][d - G[i].d].num + G[i].p; dp[a][b][c][d].c = dp[a - G[i].a][b - G[i].b][c - G[i].c][d - G[i].d].c | (1ULL << i); } if(a && dp[a][b][c][d].num < dp[a - 1][b][c][d].num){ dp[a][b][c][d] = dp[a - 1][b][c][d]; } if(b && dp[a][b][c][d].num < dp[a][b - 1][c][d].num){ dp[a][b][c][d]= dp[a][b - 1][c][d]; } if(c && dp[a][b][c][d].num < dp[a][b][c - 1][d].num){ dp[a][b][c][d] = dp[a][b][c - 1][d]; } if(d && dp[a][b][c][d].num < dp[a][b][c][d - 1].num){ dp[a][b][c][d]= dp[a][b][c][d - 1]; } } } } } } ULL t = dp[A][B][C][D].c; For(i,1,N){ if(t & (1ULL << i)) P.push_back(i); } printf("%d ",P.size()); for(int i = 0 ; i < P.size(); i ++){ printf("%d ",P[i] - 1); } return 0; }