需要注意的一个细节是 s0 s1 s2改变后,不能再用 d[i][s1][s2] 来更新dp值。最好用引用来简化代码并减少出错。
Run Time: 0.549s
#define UVa "LT9-15.10817.cpp" //Headmaster's Headache char fileIn[30] = UVa, fileOut[30] = UVa; #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #include<iostream> #include<sstream> #include<string> using namespace std; //Global Variables. Reset upon Each Case! const int maxs = 8, maxm = 20 + 5, maxn = 100 + 5; const int INF = 10000000; int S, M, N; int cost[maxm + maxn]; int subject[maxm + maxn]; int d[maxn+maxm][(1<<maxs)][1<<maxs]; ///// int dp(int i, int s0, int s1, int s2) { if(i >= N + M) { if(s0 != 0 || s1 != 0) return INF; return 0; } if(d[i][s1][s2] != -1) return d[i][s1][s2]; int& ans = d[i][s1][s2] = INF; if(i >= M) ans = dp(i+1, s0, s1, s2); int t1 = s0 & subject[i]; //0 -> 1 int t2 = s1 & subject[i]; //1 -> 2 s0 = s0^t1; s1 = (s1^t2) | t1; s2 = s2 | t2; ans = min(ans, dp(i + 1, s0, s1, s2) + cost[i]); return ans; } int main() { while(cin>>S>>M>>N && S) { getchar(); memset(subject, 0, sizeof(subject)); memset(d, -1, sizeof(d)); int a; for(int i = 0; i < M + N; i ++) { string line; getline(cin, line); stringstream ss(line); ss>>cost[i]; while(ss>>a) subject[i] |= 1<<(a-1); //subject number starting from 0. } cout<<dp(0, (1<<S)-1, 0, 0)<<endl; } return 0; }