取石子游戏 HDU2516(斐波那契博弈)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2516

题目:

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 Input
2 13 10000 0
 

 

Sample Output
Second win Second win First win
 
思路:斐波那契博弈裸题,先手必胜的条件为n不是一个斐波那契数。因此,我们先打表,求出1~2^31次方内的所有斐波那契数求出来,然后一边循环即可,因为易知斐波那契数列增长极快,到50项左右时就已经爆int了,所以进行遍历时复杂度为常数级。
代码实现如下:
 1 #include <cstdio>
 2 
 3 int n;
 4 int a[55];
 5 
 6 void init() {
 7     a[0] = 2, a[1] = 3;
 8     for(int i = 2; i <= 45; i++) {
 9         a[i] = a[i-1] + a[i-2];
10     }
11 }
12 
13 int main() {
14     init();
15     while(~scanf("%lld", &n) && n) {
16         int flag = 1;
17         for(int i = 0; i <= 45; i++) {
18             if(a[i] == n) {
19                 puts("Second win");
20                 flag = 0;
21                 break;
22             }
23         }
24         if(flag) puts("First win");
25     }
26     return 0;
27 }

 

posted @ 2018-05-05 22:00  Dillonh  阅读(373)  评论(0编辑  收藏  举报