求Grundy值的时候集合最好用数组,因为set有可能超时。
题意:
两人在1*n的格子纸上轮流打叉,最先打出连续3个叉者获胜,两个人的叉都是一样的。
输入
3 //表示n=3
6 //表示n=6
输出
1 //表示先手必胜
2 //表示先手必败
思路:
求grundy值就好了
代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <vector>
#include <map>
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
using namespace std;
int n, sg[2111];//,s[2111];
int dfs(int x) {
if (x <= 0)return 0;
if (sg[x] != -1)return sg[x];
//memset(s, 0, sizeof(s));
//不能用全局变量加memset,因为dfs到下一层之后s就变了
int s[2111] = { 0 };
for (int i = 1; i <= x; i++)
s[dfs(i - 3) ^ dfs(x - i - 2)] = 1;
while (s[++sg[x]]);
return sg[x];
}
int main(){
memset(sg, -1, sizeof(sg));
while (scanf("%d", &n)!=EOF)
printf("%d\n", dfs(n) ? 1 : 2);
return 0;
}

本文介绍了一种使用Grundy值解决两人轮流在1*n格子纸上打叉游戏的方法,目标是使一方首先形成连续三个叉以获胜。通过递归求解Grundy值并运用动态规划技巧,文章提供了C++代码实现,展示了如何高效地判断先手玩家是否必胜。
1872

被折叠的 条评论
为什么被折叠?



