题目:Alice and Bob like playing games. There are two piles of stones with numbers {n}n and {m}m. Alice and Bob take turns to operate, each operation can take away {k}(k>0)k(k>0) stones from one pile and take away s \times k(s \geq 0)s×k(s≥0) stones from another pile. Alice plays first. The person who cannot perform the operation loses the game.
Please determine who will win the game if both Alice and Bob play the game optimally.
大意:两人博弈,每次一个人从一堆中拿 k 个,同时从另一堆拿 k * s(s >= 0) 个,问谁先不能拿。
代码:
#include<bits/stdc++.h>
using namespace std;
bool dp[5005][5005];
int t,n,m;
void pre()//预处理打表由最初必败状态出发并标记上一步必胜的状态。
{
for(int i=0;i<=5000;i++){
for(int j=0;j<=5000;j++){
if(!dp[i][j]){
for(int k=1;i+k<=5000;k++){
for(int l=0;j+l*k<=5000;l++){
dp[i+k][j+l*k]=1;
}
}
for(int k=1;j+k<=5000;k++){
for(int l=0;i+l*k<=5000;l++){
dp[i+l*k][j+k]=1;
}
}
}
}
}
}
int main()
{
pre();
cin>>t;
while(t--){
cin>>n>>m;
if(dp[n][m]){//查表
cout<<"Alice"<<endl;
}
else{
cout<<"Bob"<<endl;
}
}
return 0;
}
本文介绍了一种两人博弈游戏的算法实现,通过预处理和动态规划的方法确定初始状态下哪方玩家将赢得游戏。代码详细展示了如何构建解决方案,并利用查表的方式快速判断结果。

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



