#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
char a[1e6+11];
int main()
{
stack<char> stk;
scanf("%s",a);
int left=0,right=0; //统计左括号和右括号的个数,不同也不可能
int num=0,flag=1,l;
l=strlen(a);
for(int i=0;i<l;i++)
{
if(a[i]=='<'||a[i]=='('||a[i]=='{'||a[i]=='[')
{
left++;
stk.push(a[i]);
}
else if(a[i]=='>')
{
right++;
if(stk.empty())
{
flag=0;
break;
}
else if(stk.top()=='<') //配对弹出
stk.pop();
else
{
num++; //不配对,更换,num+1
stk.pop();
}
}
else if(a[i]==')')
{
right++;
if(stk.empty())
{
flag=0;
break;
}
else if(stk.top()=='(')
stk.pop();
else
{
num++;
stk.pop();
}
}
else if(a[i]==']')
{
right++;
if(stk.empty())
{
flag=0;
break;
}
else if(stk.top()=='[')
stk.pop();
else
{
num++;
stk.pop();
}
}
else if(a[i]=='}')
{
right++;
if(stk.empty())
{
flag=0;
break;
}
else if(stk.top()=='{')
stk.pop();
else
{
num++;
stk.pop();
}
}
}
if(left!=right)
flag=0;
if(flag==1)
printf("%d\n",num);
else
printf("Impossible\n");
return 0;
}
【Codeforces】-612C-Replace To Make Regular Bracket Sequence(括号配对,栈)
最新推荐文章于 2018-09-18 22:19:34 发布