取石子游戏
链接 http://acm.hdu.edu.cn/showproblem.php?pid=2516
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10199 Accepted Submission(s): 6177
Problem Description
1堆石子有n个,两人轮流取.先取者第1次可以取任意多个,但不能全部取完.以后每次取的石子数不能超过上次取子数的2倍。取完者胜.先取者负输出"Second win".先取者胜输出"First win".
Input
输入有多组.每组第1行是2<=n<2^31. n=0退出.
Output
先取者负输出"Second win". 先取者胜输出"First win".
参看Sample Output.
参看Sample Output.
Sample Input
2 13 10000 0
Sample Output
Second win Second win First win
思路:从1枚举石子个数,找到规律,当n为斐波拉契数时后手胜,否则先手胜
因为int型开数组会爆掉,所以通过变量代替数组
代码如下:
#include<iostream> #include<cstdio> using namespace std; #define ll long long int int main() { int n; while(scanf("%d",&n)&&n) { int ans1=2,ans2=3; if(n==2||n==3) { cout<<"Second win"<<'\n'; } else { bool flag=true; for(;n>ans1;) { if(n==ans1+ans2) { cout<<"Second win"<<'\n'; flag=false; break; } int temp=ans1; ans1=ans2;ans2=temp+ans2; } if(flag) cout<<"First win"<<'\n'; } } }