题目:http://community.topcoder.com/stat?c=problem_statement&pm=12394
递归,搜索所有情况。
代码:
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
using namespace std;
/*************** Program Begin **********************/
class EllysCandyGame {
public:
int N;
vector <int> sweets;
int isFirstWin(int w1, int w2)
{
bool ok = false;
int res = 1;
for (int j = 0; j < N; j++) {
if (sweets[j] != 0) {
ok = true;
if (j - 1 >= 0) {
sweets[j-1] = 2 * sweets[j-1];
}
if (j + 1 < N) {
sweets[j+1] = 2 * sweets[j+1];
}
int take = sweets[j];
sweets[j] = 0;
int nres = isFirstWin(w2 + take, w1);
if (1 == nres) {
if (j - 1 >= 0) {
sweets[j-1] = sweets[j-1] / 2;
}
if (j + 1 < N) {
sweets[j+1] = sweets[j+1] / 2;
}
sweets[j] = take;
return -1;
}
if (0 == nres) {
res = 0;
}
if (j - 1 >= 0) {
sweets[j-1] = sweets[j-1] / 2;
}
if (j + 1 < N) {
sweets[j+1] = sweets[j+1] / 2;
}
sweets[j] = take;
}
}
if (!ok) { // 结束
if (w1 == w2) {
return 0;
}
if (w1 > w2) {
return 1;
}
if (w1 < w2) {
return -1;
}
}
return res;
}
string getWinner(vector <int> sw) {
string res;
this->N = sw.size();
this->sweets = sw;
int r = -1;
bool noChoice = true;
for (int i = 0; i < N; i++) {
if (sweets[i] != 0) { // 起始选择
noChoice = false;
if (i - 1 >= 0) {
sweets[i-1] = 2 * sweets[i-1];
}
if (i + 1 < N) {
sweets[i+1] = 2 * sweets[i+1];
}
int take = sweets[i];
sweets[i] = 0;
int rt = isFirstWin(take, 0);
if (rt == 1) {
r = 1;
break;
} else if (rt == 0) {
r = 0;
}
if (i - 1 >= 0) {
sweets[i-1] = sweets[i-1] / 2;
}
if (i + 1 < N) {
sweets[i+1] = sweets[i+1] / 2 ;
}
sweets[i] = take;
}
}
if (noChoice) {
return "Draw";
}
if (r == 0) {
return "Draw";
}
if (r == 1) {
return "Elly";
}
if (r == -1) {
return "Kris";
}
return res;
}
};
/************** Program End ************************/