Luo Gu P1241 parentheses sequence (stack)

Ok...

 

Topic link: https: //www.luogu.org/problem/P1241

 

First, this question is an enhanced version of the stack entry questions, not only want you to judge the legality of the brackets sequence, you will have to complete this sequence complementary ...

The beginning is no clue, after seeing tj suddenly realized ...

 

Ideas:

We assume that all the brackets are not legitimate, that did not match, then we sweep again from scratch, to deal with the left bracket is relatively simple:

All subscripts q is stored in the left hand bracket stack, and then left bracket and right bracket corresponding to all stored in the array b.

Then, for more complex processing right parenthesis:

If the previous match have left parenthesis or left parenthesis top of the stack does not match, then the right bracket matches other match, ie, the array corresponding position to put a parenthesis b. If a match is then stored in the array b right parenthesis cleared.

Note the order when the output ...

 

AC Code:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 char s[105], b[105];
 8 int q[105], cnt;
 9 
10 int main(){
11     scanf("%s", s);
12     int l = strlen(s);
13     for(int i = 0; i < l; i++){
14         if(s[i] == '(') {q[++cnt] = i; b[i] = ')'; continue;}
15         if(s[i] == '[') {q[++cnt] = i; b[i] = ']'; continue;}
16         if(s[i] == ')' || s[i] == ']'){
17             if(!cnt || b[q[cnt]] != s[i]){
18                 if(s[i] == ')') b[i] = '(';
19                 else b[i] = '[';
20             }
21             else b[q[cnt--]] = ' ';
22         }
23     }
24     for(int i = 0; i < l; i++){
25         if(b[i] == '(' || b[i] == '[') printf("%c", b[i]);
26         printf("%c", s[i]);
27         if(b[i] == ')' || b[i] == ']') printf("%c", b[i]);
28     }
29     return 0;
30 }
AC Code

 

Guess you like

Origin www.cnblogs.com/New-ljx/p/11284700.html