BNUOJ 5997 Fibonacci again and again

Fibonacci again and again

Time Limit: 1000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 1848
64-bit integer IO format: %I64d      Java class name: Main
 
任何一个大学生对菲波那契数列(Fibonacci numbers)应该都不会陌生,它是这样定义的:
F(1)=1;
F(2)=2;
F(n)=F(n-1)+F(n-2)(n>=3);
所以,1,2,3,5,8,13……就是菲波那契数列。
在HDOJ上有不少相关的题目,比如1005 Fibonacci again就是曾经的浙江省赛题。
今天,又一个关于Fibonacci的题目出现了,它是一个小游戏,定义如下:
1、  这是一个二人游戏;
2、  一共有3堆石子,数量分别是m, n, p个;
3、  两人轮流走;
4、  每走一步可以选择任意一堆石子,然后取走f个;
5、  f只能是菲波那契数列中的元素(即每次只能取1,2,3,5,8…等数量);
6、  最先取光所有石子的人为胜者;

假设双方都使用最优策略,请判断先手的人会赢还是后手的人会赢。
 

Input

输入数据包含多个测试用例,每个测试用例占一行,包含3个整数m,n,p(1<=m,n,p<=1000)。
m=n=p=0则表示输入结束。
 

Output

如果先手的人能赢,请输出“Fibo”,否则请输出“Nacci”,每个实例的输出占一行。
 

Sample Input

1 1 1
1 4 1
0 0 0

Sample Output

Fibo
Nacci

Source

 
解题:SG函数
 

对于一个给定的有向无环图,定义关于图的每个顶点的 Sprague-Grundy 函数g如下:g(x)=mex{ g(y) | y是x的后继 },这里的g(x)即sg[x]

例如:取石子问题,有1堆n个的石子,每次只能取{1,3,4}个石子,先取完石子者胜利,那么各个数的SG值为多少?

sg[0]=0,f[]={1,3,4},

x=1时,可以取走1-f{1}个石子,剩余{0}个,mex{sg[0]}={0},故sg[1]=1;

x=2时,可以取走2-f{1}个石子,剩余{1}个,mex{sg[1]}={1},故sg[2]=0;

x=3时,可以取走3-f{1,3}个石子,剩余{2,0}个,mex{sg[2],sg[0]}={0,0},故sg[3]=1;

x=4时,可以取走4-f{1,3,4}个石子,剩余{3,1,0}个,mex{sg[3],sg[1],sg[0]}={1,1,0},故sg[4]=2;

x=5时,可以取走5-f{1,3,4}个石子,剩余{4,2,1}个,mex{sg[4],sg[2],sg[1]}={2,0,1},故sg[5]=3;

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <climits>
 7 #include <vector>
 8 #include <queue>
 9 #include <cstdlib>
10 #include <string>
11 #include <set>
12 #include <stack>
13 #define LL long long
14 #define pii pair<int,int>
15 #define INF 0x3f3f3f3f
16 using namespace std;
17 const int maxn = 1010;
18 int f[maxn] = {1,2},sg[maxn];
19 bool vis[maxn];
20 void init(){
21     int i,j;
22     for(i = 2; f[i-1] <= 1000 && i <= 1000; i++)
23         f[i] = f[i-1]+f[i-2];
24     memset(sg,0,sizeof(sg));
25     for(i = 0; i <= 1000; i++){
26         memset(vis,false,sizeof(vis));
27         for(j = 0; f[j] <= i; j++)
28             vis[sg[i-f[j]]] = true;
29         for(j = 0; j <= 1000; j++)
30             if(!vis[j]){
31                 sg[i] = j;
32                 break;
33             }
34     }
35 }
36 int main() {
37     init();
38     int a,b,c;
39     while(scanf("%d %d %d",&a,&b,&c),a||b||c){
40         if(sg[a]^sg[b]^sg[c]) puts("Fibo");
41         else puts("Nacci");
42     }
43     return 0;
44 }
View Code
原文地址:https://www.cnblogs.com/crackpotisback/p/3908524.html