POJ

来源:互联网 发布:程序员加薪 压力大 编辑:程序博客网 时间:2024/04/30 01:28
Two Ends POJ - 2738 

In the two-player game "Two Ends", an even number of cards is laid out in a row. On each card, face up, is written a positive integer. Players take turns removing a card from either end of the row and placing the card in their pile. The player whose cards add up to the highest number wins the game. Now one strategy is to simply pick the card at the end that is the largest -- we'll call this the greedy strategy. However, this is not always optimal, as the following example shows: (The first player would win if she would first pick the 3 instead of the 4.) 
3 2 10 4 
You are to determine exactly how bad the greedy strategy is for different games when the second player uses it but the first player is free to use any strategy she wishes.
Input
There will be multiple test cases. Each test case will be contained on one line. Each line will start with an even integer n followed by n positive integers. A value of n = 0 indicates end of input. You may assume that n is no more than 1000. Furthermore, you may assume that the sum of the numbers in the list does not exceed 1,000,000.
Output
For each test case you should print one line of output of the form: 
In game m, the greedy strategy might lose by as many as p points. 
where m is the number of the game (starting at game 1) and p is the maximum possible difference between the first player's score and second player's score when the second player uses the greedy strategy. When employing the greedy strategy, always take the larger end. If there is a tie, remove the left end.
Sample Input
4 3 2 10 48 1 2 3 4 5 6 7 88 2 2 1 5 3 8 7 30
Sample Output
In game 1, the greedy strategy might lose by as many as 7 points.In game 2, the greedy strategy might lose by as many as 4 points.In game 3, the greedy strategy might lose by as many as 5 points.

思路:DP,用d[i][j]表示在[i,j]这个区间所能得到的最大分数。(可以用递推写,也可以用for循环来写)。

#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;int a[1001],d[1001][1001];int dfs(int st,int en){if(st>en)return 0;if(d[st][en]!=0)return d[st][en];//取a[st]这个数 if(a[st+1]>=a[en])d[st][en]=max(d[st][en],a[st]+dfs(st+2,en));else d[st][en]=max(d[st][en],a[st]+dfs(st+1,en-1));//取a[en]这个数 if(a[st]>=a[en-1])d[st][en]=max(d[st][en],a[en]+dfs(st+1,en-1));else d[st][en]=max(d[st][en],a[en]+dfs(st,en-2));return d[st][en];}int main(){int n,cas=1,sum=0;while(scanf("%d",&n)!=EOF&&n){sum=0;memset(d,0,sizeof d);for(int i=0;i<n;i++)cin>>a[i],sum+=a[i];printf("In game %d, the greedy strategy might lose by as many as %d points.\n",cas++,2*dfs(0,n-1)-sum);}return 0;}


原创粉丝点击