sicily 1176 Two Ends dp(记忆化搜索)

今天在网络中心上班,看到他们在做这题,吃饭后我也来做,刚开始看,就直接想暴力dfs,看了一下status,130个TLE,断定不行了,哈哈,我算法分析不行,只能这样看。

然后想了一下,其实也是最优问题,dp可以解决,不过还是WA了一次,因为没留意When employing the greedy strategy, always take the larger end. If there is a tie, remove the left end.这个条件。加等号就A了

#include <iostream> #include <cstdio> #include <cstring> using namespace std; int n; int num[1001]; int sum; int f[1001][1001]; int dp(int beg, int end) { if(f[beg][end] == 0) { if(beg == end - 1) //剩下两个数的时候真的要贪心了 return f[beg][end] = max(num[beg], num[end]); //分情况讨论 int tmp1 = num[beg]; if(num[beg + 1] >= num[end]) //注意等号,如果两个边相等,则取左边 tmp1 += dp(beg + 2, end); else tmp1 += dp(beg + 1, end - 1); int tmp2 = num[end]; if(num[beg] >= num[end - 1]) tmp2 += dp(beg + 1, end - 1); else tmp2 += dp(beg, end - 2); f[beg][end] = max(tmp1, tmp2); return f[beg][end]; } return f[beg][end]; } int main() { //freopen("1.txt", "r", stdin); int count = 1; while(scanf("%d", &n) != EOF && n != 0) { sum = 0; memset(f, 0, sizeof(f)); for(int i = 0; i < n; i++) { scanf("%d", &num[i]); sum += num[i]; } printf("In game %d, the greedy strategy might lose by as many as %d points./n", count++, 2 * dp(0, n - 1) - sum); //得分相减 } return 0; } 

你可能感兴趣的:(sicily 1176 Two Ends dp(记忆化搜索))