Constraints
Time Limit: 1 secs, Memory Limit: 64 MB
Description
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 4 8 1 2 3 4 5 6 7 8 8 2 2 1 5 3 8 7 3 0
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.
Solution:
题目大意就是说取牌的时候用贪心,然后最多输多少分,贪心为后者使用的方法,一开始我是打算直接模拟的,然后考虑到选择的多种,写着写着就想到用递归暴力穷举应该是ok的。然后写出了递归结果超时了,用记忆化搜索就ok啦~。
#include <iostream>
#include <cstring>
using namespace std;
int card[1005], ans[1005][1005];//保存搜索结果,记忆化搜索的key
int get_max(int i, int j)
{
if (i >= j) return 0;
if (ans[i][j] != 0) return ans[i][j];
int r, l;
if (card[i+1] < card[j]) l = get_max(i+1, j-1) + card[i];//前手取左边牌的模拟
else l = get_max(i+2, j) + card[i];
if (card[i] < card[j-1]) r = get_max(i, j-2) + card[j];//前手取右边牌的模拟
else r = get_max(i+1, j-1) + card[j];
return ans[i][j] = max(r, l);
}
int main()
{
int n, c = 0;
while (cin >> n && n)
{
int i, sum = 0;
memset(ans, 0, sizeof(ans));
for (i = 0; i < n; ++i)
{
cin >> card[i];
sum += card[i];
}
cout << "In game "<< ++c;
cout <<", the greedy strategy might lose by as many as "<< 2 * get_max(0, n-1) - sum;
cout <<" points.\n";
}
return 0;
}