Codeforce612C

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.

Example
Input
[<}){}
Output
2
Input
{()}[]
Output
0
Input
]]
Output
Impossible

题目大意:给出一个括号序列,要求替换若干括号使原括号变成正则括号序列(即合法的匹配序列)。替换只能将左括号替换成不同类型的左括号,右括号替换成不同类型的右括号。问最少的替换个数,如果不存在这样的替换则输出 Impossible

题解:先打表,把情况列出来,然后用数组模拟栈操作

AC代码为:


#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#define max 1000005

int top=0;
char str[max];

int judge(char s1,char s2)
{
	if(s1=='[' && s2==']')
		return 1;
	else if(s1=='{' && s2=='}')
		return 1;
	else if(s1=='(' && s2==')')
		return 1;
	else if(s1=='<' && s2=='>')
		return 1;
	else if((s1=='<'||s1=='['||s1=='{'||s1=='(')&&(s2=='>'||s2==']'||s2=='}'||s2==')')) 
		return 2;
	else
		return 0;
}

int main()
{
	char ch;
	int num=0;
	scanf("%c",&ch);
	str[top++]=ch;
	while(scanf("%c",&ch)!=EOF && ch!='\n')		
	{
		str[top++]=ch;
		if(judge(str[top-2],str[top-1])==1)
		{
			top-=2;
		}
		else if(judge(str[top-2],str[top-1])==2)
		{
			top-=2;
			num++;
		}	
	}
	if(top)
		printf("Impossible\n");
	else
		printf("%d\n",num);
		return 0;
	
} 

posted @ 2018-01-24 20:39  StarHai  阅读(203)  评论(0编辑  收藏  举报