【1】巴什博弈
有一堆石子共有N个。A B两个人轮流拿,A先拿。每次最少拿1颗,最多拿K颗,拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出N和K,问最后谁能赢得比赛。
例如N = 3,K = 2。无论A如何拿,B都可以拿到最后1颗石子。
题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1066
代码实现:
//Bash
#include<iostream>
using namespace std;
int main(int argc,char * argv[])
{
ios::sync_with_stdio(false);
int t,n,k;
cin>>t;
while(t--)
{
cin>>n>>k;
if(n%(k+1) == 0) //只需要判断n是否能整除k+1,若是可以输出后手,否则先手
cout<<'B'<<endl;
else
cout<<'A'<<endl;
}
return 0;
}
【2】威佐夫博弈
有2堆石子。A B两个人轮流拿,A先拿。每次可以从一堆中取任意个或从2堆中取相同数量的石子,但不可不取。拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出2堆石子的数量,问最后谁能赢得比赛。
例如:2堆石子分别为3颗和5颗。那么不论A怎样拿,B都有对应的方法拿到最后1颗。
题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1072
代码实现:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,x,y;
cin>>t;
while(t--)
{
cin>>x>>y;
if(x>y)
swap(x,y);
int mm = (y-x)*(1+sqrt(5.0))/2.0;
if(mm == x)
cout<<'B'<<endl;
else
cout<<'A'<<endl;
}
return 0;
}
【3】尼姆博弈
有N堆石子。A B两个人轮流拿,A先拿。每次只能从一堆中取若干个,可将一堆全取走,但不可不取,拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出N及每堆石子的数量,问最后谁能赢得比赛。
例如:3堆石子,每堆1颗。A拿1颗,B拿1颗,此时还剩1堆,所以A可以拿到最后1颗石子。
题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1069
代码实现:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n,ans=0,stone;
cin>>n;
for(int i=1;i<=n;i++) //把所有结果异或起来
{
cin>>stone;
ans^=stone;
}
if(ans == 0) //异或之后的结果为0则后手胜,否则先手胜
cout<<'B'<<endl;
else
cout<<'A'<<endl;
return 0;
}
【4】斐波那契博弈
1堆石子有n个,两人轮流取.先取者第1次可以取任意多个,但不能全部取完.以后每次取的石子数不能超过上次取子数的2倍。取完者胜.先取者负输出"Second win".先取者胜输出"First win"
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2516
思路:看所给的数据是不是斐波那契数列中的某一个数,若是的话,后手胜,否则,先手胜利。
代码实现:
#include<iostream>
using namespace std;
typedef long long ll;
const int maxn = 1e6+100;
ll a[maxn];
void solve()
{
a[0] = a[1] = 1;
for(int i=2;i<=100;i++)
a[i] = a[i-1] + a[i-2];
}
int main()
{
ios::sync_with_stdio(false);
int n;
solve();
while(cin>>n&&n)
{
int flag = 0;
for(int i=0;i<=100;i++)
{
if(a[i] == n)
{
flag = 1;
break;
}
}
if(!flag)
cout<<"First win"<<endl;
else
cout<<"Second win"<<endl;
}
return 0;
}