H - Streets of Working Lanterns Gym - 101149H -括號匹配-棧模擬
阿新 • • 發佈:2018-12-01
-
H - Streets of Working Lanterns
- Gym - 101149H
- 題意:括號匹配,有很多"?",這些"?"可以湊成任意一種,判斷最後能否恢復成匹配模式的括號
- 思路:更改"?".肯定與位置有關所以需要儲存,入棧同時要保留位置,然後先進行原來的括號匹配 。
- 匹配完之後進行“?”湊數,一定要注意位置關係,此時棧內如果還有沒匹配的括號,那應該先把它們的
- 順序反轉一下,這樣便於接下來儘可能地讓前面的“?”去跟“)”匹配,後面的“?”與“(”去匹配。
- 如果整個過程都能順利進行的話,最後檢驗一下剩下的"?"數目是否是偶數即可。
-
#include<bits/stdc++.h> using namespace std; string str; int sum,len,s1,s2,s3,s4,s,ord,cnt,R,L; vector<int>q; vector<int>pp; int main() { ios::sync_with_stdio(false); cin>>str; stack<pair<char,int> >stk,st; len=str.size(); for(int i=0; i<len; i++) { if(str[i]=='?') { q.push_back(i); sum++; continue; } if(st.empty()) st.push(make_pair(str[i],i)); else { if(st.top().first=='('&&str[i]==')') st.pop(); else st.push(make_pair(str[i],i)); } } while(!st.empty()) { stk.push(st.top()); st.pop(); } s=stk.size(); if(sum<s) cout<<"Impossible"<<endl; else { bool flag=0; sort(q.begin(),q.end()); while(!stk.empty()) { if(L==sum) { flag=1; break; } ord=stk.top().second; if(stk.top().first==')'&&L<sum) { if(ord>q[L]) { str[q[L]]='('; L++; stk.pop(); } else { flag=1; break; } } else if(stk.top().first=='('&&L<sum) { if(ord<q[L]) { str[q[L]]=')'; L++; stk.pop(); } else pp.push_back(q[L++]); } } if(flag) cout<<"Impossible"<<endl; else { if(s!=0) for(int i=L; i<sum; i++) pp.push_back(q[i]); R=pp.size(); if(R==0) { if(L==sum) cout<<str<<endl; else { if(sum%2==1) cout<<"Impossible"<<endl; else { for(int i=0; i<sum/2; i++) str[q[i]]='('; for(int i=sum/2; i<sum; i++) str[q[i]]=')'; cout<<str<<endl; } } } else { if(R%2==1) cout<<"Impossible"<<endl; else { for(int i=0; i<R/2; i++) str[pp[i]]='('; for(int i=R/2; i<R; i++) str[pp[i]]=')'; cout<<str<<endl; } } } } return 0; }