博弈取石子總結

1.一堆石子共有n個,A先手拿,B後手,要求每次最少拿1,最多拿k,拿到最後一個的獲勝
如果n <= k,A勝!
如果n%(k+1)==0,B勝!
否則A勝

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n,k;
	cin >> n >> k;
	if(n <= k) cout << "A" << endl;
	if(n % (k+1) == 0) cout << "B" << endl;
	else cout << "A" << endl;
	return 0;
}

2.一堆石子共有n個,A先手,B後手,要求每一次只能拿1.3.或者4個,拿到最後一個的獲勝
如果n%7等於0或2,A勝!
否則B勝!

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	if(n % 7 == 0 || n % 7 == 2)
	cout << "A" << endl;
	else cout << "B" << endl;
	return 0;
}

3.尼姆博弈!!!
n堆石子,A先手,每次在一堆裏面取任意,不可不取,拿到最後一個獲勝

所有石子堆的石子個數的異或和:a[0] xor a[1] xor … a[n],異或和爲0,則B勝
異或和不爲0,A勝

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 50;
int a[maxn];
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	int ans = 0;
	for(int i = 0; i < n; i++)
	{
		cin >> a[i];
		ans ^= a[i];
	}
	if(ans == 0) cout << "B" << endl;
	else
	cout << "A" << endl;
	return 0;
}

4.威佐夫博弈!!!
有兩堆石子,A先手,B後手,每次在兩堆石子取相同個數或者只在一堆取,不可不取,拿到最後一個獲勝

兩堆個數爲a,b,交換使得a小於等於b
計算 int t = (int)((1.0+sqrt(5.0)) / 2.0 * (b-a))
如果t等於a,B勝
如果t等於b,A勝

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int a,b;
	cin >> a >> b;
	int t  = (int)((1.0 + sqrt(5.0)) / 2.0 * (b-a));
	if(t == a) cout << "B" << endl;
	else cout << "A" << endl;
	return 0;
}

5.斐波那鍥博弈!!!
一堆石子有n個,A先手,B後手,先手第一次可以隨便拿(但是不可不拿,不可全拿),之後每一次拿最少拿1個,最多不超過上一次拿的2倍,拿到最後一個石子獲勝

如果n爲斐波那鍥數,那麼先手必敗,B獲勝
否則A勝

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1e5 + 50;
int a[maxn];
int vis[maxn] = {0};
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	a[0] = 1;
	a[1] = 1;
	vis[1] = 1;
	for(int i = 2; i < maxn; i++)
	{
		a[i] = a[i-1] + a[i+1];
		vis[a[i]] = 1;
	}
	if(vis[n]) cout << "B" << endl;
	else cout << "A" << endl;
	return 0;
}

留着給自己看,奧利給!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章