http://vjudge.net/contest/view.action?cid=46225#problem/H
Two players, S and T, are playing a game where they make alternate moves. S plays first.
In this game, they start with an integer N. In each move, a player removes one digit from the integer and passes the resulting number to the other player. The game continues in this fashion until a player finds he/she has no digit to remove when that player is declared as the loser.
With this restriction, it’s obvious that if the number of digits in N is odd then S wins otherwise T wins. To make the game more interesting, we apply one additional constraint. A player can remove a particular digit if the sum of digits of the resulting number is a multiple of 3 or there are no digits left.
Suppose N = 1234. S has 4 possible moves. That is, he can remove 1, 2, 3, or 4. Of these, two of them are valid moves.
- Removal of 4 results in 123 and the sum of digits = 1 + 2 + 3 = 6; 6 is a multiple of 3.
- Removal of 1 results in 234 and the sum of digits = 2 + 3 + 4 = 9; 9 is a multiple of 3.
The other two moves are invalid.
If both players play perfectly, who wins?
Input
The first line of input is an integer T(T<60) that determines the number of test cases. Each case is a line that contains a positive integer N. N has at most 1000 digits and does not contain any zeros.
Output
For each case, output the case number starting from 1. If S wins then output ‘S’ otherwise output ‘T’.
Sample Input Output for Sample Input
3 | Case 1: S |
两个人取数,规则是每当一个人取过之后要么没有数了,要么剩下的数的和为3的倍数,两个人都采取最优的策略。
当n=1先手胜。n>1时,第一个人取候剩下的数是3的倍数,那么第二人去这能取走是三的倍数的一个数,否则无法保证剩下的数是三的倍数。那么,问题就转化成了三的倍数的数的数目。如果第一个人未取时恰好是三的倍数,那么,三的倍数的数个数为奇数就是后手胜,反之先手胜。若第一个人未取时不是三的倍数,那么,三的倍数的数个数为奇数就是先手胜,反之后手胜。
代码实现:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
char a[10005];
int main()
{
int T,sum1,count1;
int tt=1;
char ans;
scanf("%d",&T);
while(T--)
{
scanf("%s",a);
int n=strlen(a);
int count=0;
int sum=0;
ans='T';
for(int i=0;i<n;i++)
{
count+=a[i]-'0';
if((a[i]-'0')%3==0)
sum++;
}
for(int i=0;i<n;i++)
{
count1=count-(a[i]-'0');//判断第一个取走哪一个数剩下的满足条件
sum1=sum;
if(count1%3==0)
{
if((a[i]-'0')%3==0)//第一个取走的是3的倍数
sum1--;
if(sum1%2==0)
{
ans='S';
break;
}
}
}
printf("Case %d: %c\n",tt++,ans);
}
return 0;
}