codeforces 612C Replace To Make Regular Bracket Sequence

C. Replace To Make Regular Bracket Sequence

 

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.

Sample test(s)
input
[<}){}
output
2
input
{()}[]
output
0
input
]]
output
Impossible

#include<cstdio>
#include<cstring>
#include<stack>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
typedef long long ll;
stack<char>S;
int check(char x,char y)
{
    if((x=='['&&y==']')||(x=='<'&&y=='>')||(x=='{'&&y=='}')||(x=='('&&y==')'))return 0;
    int tx=((x=='['||x=='<'||x=='{'||x=='(')?1:2);
    int ty=((y=='['||y=='<'||y=='{'||y=='(')?1:2);
    if(tx==1&&ty==2)return 1;
    else return 2;
}
int main()
{
    char s[maxn];
    scanf("%s",s);
    int len=strlen(s);
    if(len&1)
    {
        puts("Impossible");
        return 0;
    }
    int ans=0;
    for(int i=0;i<len;i++)
    {
        if(S.empty()){S.push(s[i]);continue;}
        int tt=check(S.top(),s[i]);
        if(tt==2){S.push(s[i]);continue;}
        else ans+=tt,S.pop();
    }
    if(S.empty())
        printf("%d\n",ans);
    else
        puts("Impossible");
    return 0;
}

 

posted on 2015-12-30 09:53    阅读(179)  评论(0编辑  收藏  举报

导航