题目:
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
思路:
思维或二分图匹配。
代码如下:
1.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
int m,n,k;
int a[150];
int ok;
int main()
{
scanf("%d",&m);
while(m--)
{
int cnt=0;
ok=0;
scanf("%d%d",&n,&k);
memset (a,0,sizeof(a));
for (int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
a[x]++;
}
for (int i=1;i<=n;i++)
{
if(a[i]==0)
{
ok=1;
break;
}
if(a[i]==1) continue;
else
{
a[i+k]+=a[i]-1;
a[i]=1;
}
}
if(ok) printf("Tom\n");
else printf("Jerry\n");
}
return 0;
}
2.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=105;
int a[maxn][maxn];
int m,n,k;
int ans=0;
int match[maxn];
int vis[maxn];
bool Find(int x)
{
for (int i=1;i<=n;i++)
{
if(!vis[i]&&a[x][i])
{
vis[i]=1;
if(match[i]==-1||Find(match[i]))
{
match[i]=x;
return true;
}
}
}
return false;
}
int alg()
{
for (int i=1;i<=n;i++)
{
memset (vis,0,sizeof(vis));
if(Find(i)) ans++;
}
return ans;
}
int main()
{
scanf("%d",&m);
while(m--)
{
ans=0;
memset (match,-1,sizeof(match));
memset (a,0,sizeof(a));
scanf("%d%d",&n,&k);
for (int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
int t=x;
while(t<=n)
{
a[i][t]=1;
t+=k;
}
}
if(alg()<n) {
printf("Tom\n");
}
else
{
printf("Jerry\n");
}
}
return 0;
}