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?
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 <= 106.
Following n lines, each line contains a nonempty string which consists only of letters 'M', 'I' and 'U'.
Total length of all strings <= 106.
Output
n lines, each line is 'Yes' or 'No'.
Sample Input
2 MI MU
Sample Output
Yes No
题目大意:给定对一个串的三种操作,问能不能由 MI 变换得到。
推一下可以发现一个 U 可以由三个 I 变换得到,每次又可以消掉两个 U,所以只需要统计一下原串中 I 的个数,一个 U 算作三个 I ,只要满足 sum + 6 * K = 二的幂次即可。
对于 2 的幂次,模 6 后可以发现,余数为1 2 4 2 4 2 4 ......而偶数模 6 的结果为 0 2 4 0 2 4......,特判一下 MI ,其他只要满足 mod 6 != 0 且为偶数即可。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e6 + 5;
char a[maxn];
int main()
{
int len,n;
scanf("%d",&n);
while(n--)
{
scanf(" %s",a);
len = strlen(a);
int nm = 0,ni = 0;
for(int i = 0;i < len; ++i)
{
if(a[i] == 'M') ++nm;
if(a[i] == 'I') ++ni;
if(a[i] == 'U') ni += 3;
}
if(nm == 1 && a[0] == 'M')
{
if((ni % 2 == 0) && (ni % 6 != 0) || ni == 1) printf("Yes\n");
else printf("No\n");
}
else printf("No\n");
}
return 0;
}