MU Puzzle HDU - 4662
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?
InputFirst 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.Outputn lines, each line is 'Yes' or 'No'.Sample Input
2 MI MU
Sample Output
Yes No
所有U都是由I换来的,而U不能再换成I,所以可以讲所有U换成I的数目进行统计,如果符合要求即可
1.相当于I的数目*2
3.相当于I的数目-6
#include <cstdio> #include <cstring> using namespace std; const int maxn = 1000000 + 10; char s[maxn]; int p[30]; void init(){ p[0] = 1; for(int i = 1; i < 30; i++) p[i] = (p[i-1] << 1); } bool solve(){ bool ok = 0; int len = strlen(s), i, Mcnt = 0, Icnt = 0; for(i = 0; i < len; i++){ if(s[i] == 'M') Mcnt++; else if(s[i] == 'I') Icnt++; else if(s[i] == 'U') Icnt += 3; } if(Mcnt == 1 && s[0] == 'M'){ for(i = 29; i >= 0; i--) if(p[i] >= Icnt && (p[i] - Icnt) % 6 == 0) { ok = 1; break; } } return ok; } int main() { int n; init(); scanf("%d", &n); getchar(); while(n--){ scanf("%s", s); if(solve()) printf("Yes\n"); else printf("No\n"); } return 0; }