又是一题T-T
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 895 Accepted Submission(s): 385
Problem Description
Suppose there are the symbols M, I, and U which can be combined to produce strings of symbols called "words". We start with one word MI, and transform it to get a new word. In each step, we can use one of the following transformation rules: 1. Double any string after the M (that is, change Mx, to Mxx). For example: MIU to MIUIU. 2. Replace any III with a U. For example: MUIIIU to MUUU. 3. Remove any UU. For example: MUUU to MU. Using these three rules is it possible to change MI into a given string in a finite number of steps?
Input
First line, number of strings, n. Following n lines, each line contains a nonempty string which consists only of letters 'M', 'I' and 'U'.
Total length of all strings <= 10 6.
Total length of all strings <= 10 6.
Output
n lines, each line is 'Yes' or 'No'.
Sample Input
2 MI MU
Sample Output
Yes No
题意:输入一段不长于10
6 位的只含有M、I、U的字符串,问你是否可以根据以下3个规则从字符串“MI”转化得到:
1.将字母M后的字符串翻倍,如:MUI->MUIUI;
2.将字符串III转化为U,如:MIII->MU;
3.将2个相邻的U删去,如:MUUI->MI;
思路:根据转化规则可知,输入字符串的首字母必须为M且M只能存在一个;
头2步操作只能执行规则1,故MI->MII->MIIII,之后的操作可执行规则1或2,若一直只执行规则1可发现I的数量增长函数是2^x(x为操作次数);
设I的值为1,因为III->U,所以U的值为3,字符串MIIII,MIU,MUI的价值均为4,由此可发现,我们只用计算字符串的价值是否符合变换规则即可,而不用知道具体 的字符串是如何的;
MIIIIIIII的价值为8,可转化为价值为2的MII,M(16)I->M(10)I->M(4)I,以此类推我们可得到符合条件的价值数列:2,4,8,10,14,16,20,22,26,28,32·······可看出符合条件的价值总是为不能被3整除的偶数。
附:还有特殊情况"MI",因为不用执行操作。
上代码:
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 char word[10000005]; 5 int main() 6 { 7 int n; 8 scanf("%d",&n); 9 for(int i=1; i<=n; i++) 10 { 11 scanf("%s",word); 12 int m=strlen(word),flag=0,sum=0; 13 for(int i=0; i<m; i++) 14 if(word[i]=='U')sum+=3; 15 else if(word[i]=='M')flag++; 16 else if(word[i]=='I')sum++; 17 if(word[0]=='M'&&flag==1&&(sum%2==0&&sum%3!=0||sum==1))printf("Yes\n"); 18 else printf("No\n"); 19 } 20 return 0; 21 }