艰苦的一题。。。
首先打表打出了100以内符合必胜的石头的数目,可观察出必败的石头数目符合菲波那契数列。也就是说,只要题目给出的石头数不是菲波那契数,则必有必胜策略。
然后就是求第二个问,如果必胜,第一步拿走的最少石头数。
假设给出n,n不是菲波那契数,则A必胜的策略就是必须逼B走到离n最近切不大于n的菲波那契数x,同时使得B不能一次就把这个菲波那契数x取完。
我们可以看出这个策略具有递归性。
为了迫使B走到x,我们就变成了对于n-x块石头,且n-x不是菲波那契数,要使得符合题目规则的情况下,使得A能够拿走n-x中的最后一块石头。这时,就可以看出问题中的n变成了n-x了。
然后就是递归的终结条件,对于某一步剩下的石头是菲波那契数,则A就可以全部拿走,这就是答案,这时B不能拿石头,进入必败状态。
/******************************************************************************* # Author : Neo Fung # Email : [email protected] # Last modified: 2012-06-15 21:56 # Filename: ZOJ2290 Game.cpp # Description : ******************************************************************************/ #ifdef _MSC_VER #define DEBUG #define _CRT_SECURE_NO_DEPRECATE #endif #include <fstream> #include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <limits.h> #include <algorithm> #include <math.h> #include <numeric> #include <functional> #include <ctype.h> using namespace std; const int kMAX=1001; const double kEPS=10E-6; int lose[kMAX]; int cnt=2; int win(const int &x) { int idx=0; for(;idx<cnt && lose[idx]<=x;++idx); --idx; if(lose[idx]==x) return x; else return win(x-lose[idx]); } int main(void) { #ifdef DEBUG freopen("../stdin.txt","r",stdin); freopen("../stdout.txt","w",stdout); #endif int n,ncase=1; memset(lose,true,sizeof(lose)); lose[0]=1; lose[1]=2; while(1) { lose[cnt]=lose[cnt-2]+lose[cnt-1]; if(lose[cnt]>100000001) break; ++cnt; } while(~scanf("%d",&n) && n) { int idx=0; for(;idx<cnt && lose[idx]<=n;++idx); --idx; if(lose[idx]==n) printf("lose\n"); else { printf("%d\n",win(n-lose[idx])); } } return 0; }