HDU - 3980 Paint Chain(sg函数)

Aekdycoin and abcdxyzk are playing a game. They get a circle chain with some beads. Initially none of the beads is painted. They take turns to paint the chain. In Each turn one player must paint a unpainted beads. Whoever is unable to paint in his turn lose the game. Aekdycoin will take the first move.

Now, they thought this game is too simple, and they want to change some rules. In each turn one player must select a certain number of consecutive unpainted beads to paint. The other rules is The same as the original. Who will win under the rules ?You may assume that both of them are so clever.
Input
First line contains T, the number of test cases. Following T line contain 2 integer N, M, indicate the chain has N beads, and each turn one player must paint M consecutive beads. (1 <= N, M <= 1000)
Output
For each case, print "Case #idx: " first where idx is the case number start from 1, and the name of the winner.

有意思有意思这题很有意思。

半年前,过年的时候,我花了好几天的时间来学sg函数,终于搞懂之后进入做题阶段,在ac了数道水题之后,遇到了这道题。不会做,百度了一下,出现一个“环形局面”,把菜鸡一只的我吓得要死,赶紧跳坑了。

现在回头做这题,实在是感觉有意思。

进入题解部分,首先分析游戏的必败必胜态,由于规则要求每次必须涂m个,则不够m个的时候必输,剩余个数减m小于m的时候必胜。

这就首先得到一个特判:一开始就不够m个,先手必败。

然后思考环的问题,如果把涂油漆的点当成消失了(事实上涂过油漆后就不会再在游戏里考虑了),发现在先手走过之后,这个环被切断了,变成了一条链,反应过来可以求解后手方而不是先手方的sg函数(先手是一个环求个鬼啊)。

再深入思考,环变链之后,如果在中间涂一刷子,这个链又被切开了!切开之后怎么办呢?这个游戏就可以看成是两个游戏了,双方要在两条链上分别分出胜负,才能知道最终的胜负状态。

由sg定理可知,游戏的总sg是其子游戏的全部异或。因此考虑可以递归求解一波,剪剪枝,求出子游戏的sg,再两两异或。

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1005;
int sg[maxn];

int grundy(int n, int m) {
	if(sg[n] != -1) {
		return sg[n];
	}
	if(n < m) {
		return sg[n] = 0;
	}
	int g = 0;
	bool vis[maxn];
	memset(vis, 0, sizeof(vis));
	for(int i = 0; i <= n - m; i++) {
		vis[grundy(n - m - i, m) ^ grundy(i, m)] = 1;
	}
	while(vis[g]) {
		++g;
	}
	return sg[n] = g;
}

int main() {
	int t, n, m, kase = 0;
	scanf("%d", &t);
	while(t--) {
		scanf("%d%d", &n, &m);
		if(n < m) {
			printf("Case #%d: ", ++kase);
			printf("abcdxyzk\n");
			continue;
		}
		memset(sg, -1, sizeof(sg));
		grundy(n - m, m);
		printf("Case #%d: ", ++kase);
		printf("%s\n", sg[n - m] ? "abcdxyzk" : "aekdycoin");
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值