1. 程式人生 > >CF 612C. Replace To Make Regular Bracket Sequence【括號匹配】

CF 612C. Replace To Make Regular Bracket Sequence【括號匹配】

pos cal set while ostream problem \n push ||

【鏈接】:CF
【題意】:給你一個只含有括號的字符串,你可以將一種類型的左括號改成另外一種類型,右括號改成另外一種右括號
問你最少修改多少次,才能使得這個字符串匹配,輸出次數
【分析】:
本題用到了棧。如果遇上左括號,就加進棧裏。如果遇上右括號,就判斷棧裏的左括號是否和它匹配,不匹配就加一。不論匹不匹配,判斷後都要讓左括號出棧。
如果最後棧不為空,或者棧在循環結束前就為空,那麽不論怎麽改變,左右括號都不可能剛好匹配。
【代碼】:

#include<cstdio>  
#include<cstring>  
#include<string>  
#include<iostream>  
#include<sstream>  
#include<algorithm>  
#include<utility>  
#include<vector>  
#include<set>  
#include<map>  
#include<queue>  
#include<cmath>  
#include<iterator>  
#include<stack>  
using namespace std;  
typedef __int64 LL;  
const int INF=1e9+7;  
const double eps=1e-7;  
const int maxn=1000000;  
char s[maxn+10];  
int n;  
  
bool isle(char x)  
{  
    return x=='('||x=='<'||x=='['||x=='{';  
}  
  
int cal(char x,char  y)  
{  
    if(x=='('&&y==')')  return 0;  
    if(x=='['&&y==']')  return 0;  
    if(x=='{'&&y=='}')  return 0;  
    if(x=='<'&&y=='>')  return 0;  
        return 1;  
}  
int work()  
{  
    n=strlen(s+1);  
    stack<int>st;  
    int ans=0;  
    for(int i=1;i<=n;i++)  
    {  
        char x=s[i];  
        if(isle(x))  st.push(i);  
        else  
        {  
            if(st.empty()) return -1;  
            int y=st.top();  
            st.pop();  
            ans+=cal(s[y],s[i]);  
  
        }  
    }  
  
    if(!st.empty())  return -1;  
  
    return ans;  
  
}  
int main()  
{  
    while(~scanf("%s",s+1))  
    {  
        int ans=work();  
        if(~ans)  printf("%d\n",ans);  
        else  puts("Impossible");  
    }  
    return 0;  
}  

CF 612C. Replace To Make Regular Bracket Sequence【括號匹配】