CodeForces 612C (STL_A题)解题报告

题目链接:http://codeforces.com/problemset/problem/612/C

--------------------------------------------------------------------------------

题意:有四种括号,按一定顺序出现,问能否完成括号的匹配,如果不能完成,最少更改几个括号能够完成括号匹配。(注意,左括号只能更换为左括号。同理右括号)

思路:本题具有这样的特征,在每次遇到括号的时候,如果不能完成括号的匹配,需要将新遇到的括号更新为比较括号,例如“{()}”,当遇到“(”时,需要将比较括号由“{”更新为“(”,由此想到利用栈的数据结构。另外,如果遇到不同类别的右括号,自然需要更改其中一位括号以完成匹配。(注意,在这种情况下,其实默认了已经完成了两个括号的匹配,所以需要将栈顶的左括号弹出)例如“{(>}”需要更新的括号数目为1。另外如果栈为空的情况下又遇到右括号,按题意属于“impossible”情况输出。本题的关键点在于由操作特性分析出所选用的合适数据结构——栈。

代码:

 1 #include<cstdio>
 2 #include<stack>
 3 #include<string>
 4 #include<iostream>
 5 #include<cmath>
 6 using namespace std;
 7 stack<char> s;
 8 char siz=0;
 9 string s1 ="0";
10 int a =0;
11 char c=0;
12 char m=0;
13 int flag = 0;
14 int head = 0;
15 int tail = 0;
16 
17 int main(void){
18     getline(cin,s1);
19     for(int i =0;i<s1.length();i++){
20         c=s1[i];
21         if(s.empty()&&(c=='>'||c=='}'||c==')'||c==']'))
22         {
23             flag = 1;
24             break;
25         }
26         else if(c=='<'||c=='{'||c=='('||c=='['){
27             s.push(c);
28             head ++;
29         }
30         else if(c=='>'){
31             if(s.top()=='<'){
32                 s.pop();
33                 tail++;
34             }else{
35                 a++;
36                 s.pop();
37             }
38         }
39         else if(c=='}'){
40             if(s.top()=='{'){
41                 s.pop();
42                 tail++;
43             }else{
44                 a++;
45                 s.pop();
46             }
47         }
48         else if(c==')'){
49             if(s.top()=='('){
50                 s.pop();
51                 tail++;
52             }else{
53                 a++;
54                 s.pop();
55             }    
56         }
57         else if(c==']'){
58             if(s.top()=='['){
59                 s.pop();
60                 tail++;
61             }else{
62                 a++;
63                 s.pop();
64             }
65         } 
66     }
67     //printf("%d %d %d",head,tail,a);
68     if(head ==tail&&(flag==0)) printf("0\n");
69     else if(abs(head-tail)==a&&(flag==0)) printf("%d\n",a);
70     else printf("Impossible");
71 
72     return 0;
73 
74 }
View Code

 

posted @ 2018-01-20 22:12  caomp  阅读(235)  评论(0)    收藏  举报