【原创】G - Replace To Make Regular Bracket Sequence【枚举(1.情况数)栈{应尽量将能合并的情况作合并处理}】
G - Replace To Make Regular Bracket Sequence
https://cn.vjudge.net/contest/173547#problem/G
You are given string s consists of opening and closing brackets of four kinds <>,{}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.
The following definition of a regular bracket sequence is well-known, so you can be familiar with it.
Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.
For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.
Determine the least number of replaces to make the string s RBS.
Input
The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.
Output
If it's impossible to get RBS from s print Impossible.
Otherwise print the least number of replaces needed to get RBS from s.
Example
[<}){}
2
{()}[]
0
]]
Impossible
代码:
1 #include<stdio.h> 2 #include<stack> 3 using namespace std; 4 char s[]="<>{}()[]",g; 5 int F(char c){ 6 for(int i=0;i<8;i++) 7 if(c==s[i]) 8 return i; 9 } 10 stack <char> S; 11 int main() 12 { 13 bool flag=true; 14 int ans=0; 15 while((g=getchar())&&g!='\n') 16 { 17 if(flag) 18 { 19 if(F(g)%2==0) 20 S.push(g); 21 else 22 { 23 if(!S.empty()) 24 { if(F(g)-F(S.top())!=1) 25 ans++; 26 S.pop(); 27 } 28 else 29 { 30 S.push('0');//随便入栈一个元素 31 flag=false; 32 } 33 } 34 } 35 } 36 if(S.empty()) 37 printf("%d\n",ans); 38 else 39 puts("Impossible"); 40 while(!S.empty()) 41 S.pop(); 42 return 0;
浙公网安备 33010602011771号