A New Stone Game
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 6463 | Accepted: 3537 |
Description
Alice and Bob decide to play a new stone game.At the beginning of the game they pick n(1<=n<=10) piles of stones in a line. Alice and Bob move the stones in turn.
At each step of the game,the player choose a pile,remove at least one stones,then freely move stones from this pile to any other pile that still has stones.
For example:n=4 and the piles have (3,1,4,2) stones.If the player chose the first pile and remove one.Then it can reach the follow states.
2 1 4 2
1 2 4 2(move one stone to Pile 2)
1 1 5 2(move one stone to Pile 3)
1 1 4 3(move one stone to Pile 4)
0 2 5 2(move one stone to Pile 2 and another one to Pile 3)
0 2 4 3(move one stone to Pile 2 and another one to Pile 4)
0 1 5 3(move one stone to Pile 3 and another one to Pile 4)
0 3 4 2(move two stones to Pile 2)
0 1 6 2(move two stones to Pile 3)
0 1 4 4(move two stones to Pile 4)
Alice always moves first. Suppose that both Alice and Bob do their best in the game.
You are to write a program to determine who will finally win the game.
Input
The input contains several test cases. The first line of each test case contains an integer number n, denoting the number of piles. The following n integers describe the number of stones in each pile at the beginning of the game, you may assume the number of stones in each pile will not exceed 100.
The last test case is followed by one zero.
Output
For each test case, if Alice win the game,output 1,otherwise output 0.
Sample Input
3 2 1 3 2 1 1 0
Sample Output
1 0
Source
题意:
A与B轮流对n堆石子进行操作,每次操作,移除1块及以上石子,并且可以把该堆的石子移到别的堆(随便移,移不移自己选择),取走最后一枚石子的胜利~
思路:
这个题也是很经典了吧,挺考验思维…我们不妨一点一点分析
n=1,肯定先手胜。
n=2,当两堆石子数相同时,后手胜(后手只要与先手操作相同即可,最后一枚石子肯定是后手移的)
n=3,先手胜,先手只要从最大的石子堆拿出一部分,剩下一部分给最小的石子堆,使其=次小的,这样就构造了两个相同的堆。
eg,1,3,5=>3,3
n=4,当两个两个堆相等时,后手胜。
反之,先手胜。先手将最大的堆削成和最小堆相等,剩下的补到次小堆,使它与次大堆相等(构造两两相等的情况)
eg.1 2 3 4->1 3 3 1。
推广:(先把石子数从小到大排序,我们的宗旨是:1,2为一组,3,4为一组……把石子凑成每一组内都相等)
若n为奇数,则先手必胜,先手可以把石子最多的一堆的石子分配给其它堆,使得其它堆两两相等。最多一堆的石子绝对是足够多,可以完成这个补齐的任务的。因为我们把石子从小到大排序后画成条形统计图。把相邻两个分成一组(1和2一组,3和4一组……)我们需要用第n堆填补1,3,5……堆我们把需要填补的这些差距(2比1高出的部分,4比3高出的部分……)投影到统计图左侧的y轴上,我们会发现这是一些不连续的区间,其长度总和明显小于第n堆。所以可以补齐。先手将最大的。
若n为偶数,
- 每组内都相等,那显然后手胜
- 反之,先手胜,先手把最大的堆削弱与最小堆相同,剩下的弥补给其他堆,使之两组两组相等,(可行性依旧画图判断)后手失败啦~
代码如下:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
#include<set>
#include<list>
using namespace std;
int a[15];
int main(){
int n;
while(scanf("%d",&n)!=EOF){
if(n==0)break;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
if(n%2){printf("1\n");continue;}
sort(a+1,a+1+n);
int flag=0;
for(int i=1;i<n;i+=2){
if(a[i]!=a[i+1]){flag=1;break;}
}
if(flag)printf("1\n");
else printf("0\n");
}
}