Game with Pearls

Problem Description
Tom and Jerry are playing a game with tubes and pearls. The rule of the game is:
1) Tom and Jerry come up together with a number K. 
2) Tom provides N tubes. Within each tube, there are several pearls. The number of pearls in each tube is at least 1 and at most N. 
3) Jerry puts some more pearls into each tube. The number of pearls put into each tube has to be either 0 or a positive multiple of K. After that Jerry organizes these tubes in the order that the first tube has exact one pearl, the 2nd tube has exact 2 pearls, …, the Nth tube has exact N pearls.
4) If Jerry succeeds, he wins the game, otherwise Tom wins. 
Write a program to determine who wins the game according to a given N, K and initial number of pearls in each tube. If Tom wins the game, output “Tom”, otherwise, output “Jerry”.
 
Input
The first line contains an integer M (M<=500), then M games follow. For each game, the first line contains 2 integers, N and K (1 <= N <= 100, 1 <= K <= N), and the second line contains N integers presenting the number of pearls in each tube.
 
Output
For each game, output a line containing either “Tom” or “Jerry”.
 
Sample Input
2 5 1 1 2 3 4 5 6 2 1 2 3 4 5 5
 
Sample Output
Jerry Tom
 
Source
 

题意:给你n个数,(1<=n<=100),还有一个k(1<=k<=n),然后允许给某一个数加上k的正整数倍,当然可以不加,问你是否可以把这n个数变成1,2,3,...,n,可以就输出Jerry,否则输出Tom。

分析:一开始直接开个100数组去记录每个数出现的次数。。。如果某一个数出现了,那就不用动这个数了,对于没出现的数,枚举要加的数(k,2k,3k,...注意边界,不能超过这个数)。如果存在某一个数没出现而且不能通过别的数加若干个k,直接判断不能实现 。。简简单单就过了

 

来源:http://mathlover.info/archives/hdu5090

 

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int m,n,k;
 9     cin>>m;
10     int a[105],cnt[102];
11     bool p[105];
12     while(m--)
13     {
14         cin>>n>>k;
15         memset(cnt,0,sizeof(cnt));
16         memset(p,0,sizeof(p));
17 
18         for(int i=0;i<n;i++)
19         {
20             cin>>a[i];
21             if(p[a[i]]==0)///判断出现的标志
22                 p[a[i]]=1;
23             else
24                 cnt[a[i]]++;///多余的数字
25         }
26 
27         bool flag=1;///标记谁能赢
28         for(int i=1;i<=n;i++)
29         {
30             if(p[i]==0)///如果这个数没有出现
31             {
32                 bool ok=0;
33                 for(int j=1;i-j*k>=1;j++)///依次减去k的倍数
34                 {
35                     if(cnt[i-j*k])///若多余
36                     {
37                         cnt[i-j*k]--;
38                         ok=1;
39                         break;///即是可以由多余的数字变化而来,逆过程
40                     }
41                 }
42                 if(!ok)///ok==0-------若果没有找到,则进行此if
43                 {
44                     flag=0;
45                     break;
46                 }
47             }
48         }
49 
50         if(flag)
51             puts("Jerry");
52         else
53             puts("Tom");
54     }
55     return 0;
56 }
 
原文地址:https://www.cnblogs.com/moqitianliang/p/4788468.html