hdu 4915 Parenthese sequence(模拟)2014多培训学校5现场
Parenthese sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)bobo would like to replace each "?
" with "(" or ")" so that the string is valid (defined as follows). Check if the way of replacement can be uniquely determined.
Note:
An empty string is valid.
If S is valid, (S) is valid.
If U,V are valid, UV is valid.
A string s1s2…sn (1≤n≤106).
If there is unique valid string, print "Unique". If there are no valid strings at all, print "None". Otherwise, print "Many".
?? ???? (??
Unique Many None
’既能够当做’(‘, 又能够当做’)‘,求有多少种方法满足括号匹配。假设不能匹配,输出“None”;假设仅仅有一种,输出“Unique”;否则输出“Many”。
’,我们能够先把这个‘?’变成‘(’,推断是否匹配。再把‘?
’变成')',推断是否匹配。
#include<cstdio> #include<cstring> const int N = 1e6 + 50; char str[N], s[N]; int len; int judge() //推断当前的字符串是否匹配 { int l = 0; //记录左括号的数量 int r = 0; //记录右括号的数量 int num = 0; //记录已经遍历过的字符数量 int i; for(i = 0; i < len; i++) //从前往后推断 { num++; if(num == 1) { if(s[i] == '?') s[i] = '('; } if(s[i] == '(') l++; else if(s[i] == ')') r++; if(r > num/2) //右括号数量太多。无法全然匹配 return 0; if(r * 2 == num) //前num个能够全然匹配 { l = r = num = 0; } } if(l > num/2) return 0; num = l = r = 0; for(i = len - 1; i >= 0; i--) //从后往前推断 { num++; if(num == 1) { if(s[i] == '?') s[i] = ')'; } if(s[i] == '(') l++; else if(s[i] == ')') r++; if(l > num / 2) return 0; //左括号数量太多,无法全然匹配 if(l * 2 == num) //后num个能够全然匹配 { l = r = num = 0; } } if(r > num/2) return 0; return 1; } int main() { int flag_l, flag_r, i; while(~scanf("%s",str)) { len = strlen(str); if(len & 1) { printf("None\n"); continue; } strcpy(s, str); flag_l = judge(); //如果没有 '?
',推断是否匹配 if(!flag_l) { printf("None\n"); continue; } for(i = 0; i < len; i++) { if(str[i] == '?') { strcpy(s, str); s[i] = ')'; flag_l = judge(); s[i] = '('; flag_r = judge(); if(flag_l && flag_r) { printf("Many\n"); break; } if(!flag_l && !flag_r) { printf("None\n"); break; } if(flag_l && !flag_r) s[i] = ')'; else if(!flag_l && flag_r) s[i] = '('; } } if(i == len) printf("Unique\n"); } return 0; }
版权声明:本文博主原创文章,博客,未经同意不得转载。