USACO A Game 解题报告

脑子真不行了。。。 明显是个动态规划,表达式都写出来了,仍然在想如何用动态规划而不用递归。。。。

最后用了Recursion with memorization,其实和动态规划也差不多,估计能好点(只计算和记录实际需要的)。

代码如下:

/*
ID: thestor1
LANG: C++
TASK: game1
*/
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cassert>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;
const int N = 100;
int n;
int num[N];
int cache[N * N];

int game(int sum, int *num, int left, int right)
{
	if(left == right)
	{
		return 0;
	}
	int index = left * (n - 1) + right;
	if(cache[index] < 0)
	{
		cache[index] = sum - max(num[left] + game(sum - num[left], num, left + 1, right), 
			num[right] + game(sum - num[right], num, left, right - 1));
	}
	return cache[index];
}

int main()
{
	FILE *fin  = fopen ("game1.in", "r");
	FILE *fout = fopen ("game1.out", "w");
	//freopen("log.txt", "w", stdout);

	//int n;
	fscanf(fin, "%d", &n);
	for(int i = 0; i < n; ++i)
	{
		fscanf(fin, "%d", &num[i]);
	}
	memset(cache, -1, n * n * sizeof(int));

	int sum = 0;
	for(int i = 0; i < n; ++i)
	{
		sum += num[i];
	}

	int player2 = game(sum, num, 0, n - 1);
	int player1 = sum - player2;
	fprintf(fout, "%d %d\n", player1, player2);
	return 0;
}


你可能感兴趣的:(USACO A Game 解题报告)