D - Replace To Make Regular Bracket Sequence

Posted wzl19981116

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D - 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

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

意思是有左右两类括号,同类可以变形,求把所有括号消掉需要变形多少次,不可以消掉就输出impossible,加个例子{[}]这个是要两次;用stack栈

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include <iomanip>
#include<cmath>
#include<float.h> 
#include<string.h>
#include<algorithm>
#define sf scanf
#define pf printf
#define mm(x,b) memset((x),(b),sizeof(x))
#include<vector>
#include<queue>
#include<stack>
#include<map>
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=a;i>=n;i--)
typedef long long ll;
typedef long double ld;
typedef double db;
const ll mod=1e9+100;
const db e=exp(1);
using namespace std;
const double pi=acos(-1.0);
char a[1000005];
int judge(int n)
{
    stack<char>v;
    int num1=0,num2=0,ans=0;
    rep(i,0,n)
    {
        if(a[i]==‘[‘||a[i]==‘(‘||a[i]==‘{‘||a[i]==‘<‘)
        v.push(a[i]);
        else
        {
            if(v.empty()) return -1;
            switch(a[i])
            {
                case ‘>‘:if(v.top()!=‘<‘) ans++;break;
                case ‘]‘:if(v.top()!=‘[‘) ans++; break;
                case ‘)‘:if(v.top()!=‘(‘) ans++; break;
                case ‘}‘:if(v.top()!=‘{‘) ans++; break;
            }
            v.pop();
        } 
    }
    if(!v.empty()) return -1;
    return ans;
}
int main()
{
    sf("%s",a);
    int len=strlen(a);
    if(len&1) { pf("Impossible"); return 0; }
    if(judge(len)==-1) pf("Impossible");
    else pf("%d",judge(len));
    return 0;
}

以上是关于D - Replace To Make Regular Bracket Sequence的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-945 Minimum Increment to Make Array Unique(使数组唯一的最小增量)

No rule to make target all'初学者求教

[LeetCode] 1249. Minimum Remove to Make Valid Parentheses

[LeetCode] 1249. Minimum Remove to Make Valid Parentheses

make: *** No rule to make target 错误原因、分析和解决办法

UltraEdit正则表达式疑问