您的位置:首页 > 产品设计 > UI/UE

CF 612 C. Replace To Make Regular Bracket Sequence 经典括号匹配+问题分解

2016-04-06 23:28 483 查看
先判断左型和右型是否匹配,如果成功,每一对括号对应的括号位置已定,然后对每一对括号分别考虑。

C. Replace To Make Regular Bracket Sequence

time limit per test
1 second

memory limit per test
256 megabytes

input
standard input

output
standard output

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)s2are
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.

Examples

input
[<}){}


output
2


input
{()}[]


output
0


input
]]


output
Impossible


#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: