avatar
fireworks99
keep hungry keep foolish

C. Replace To Make Regular Bracket Sequence

Description

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.

Examples

Input

[<}){}

Output

2

input

{()}[]

Output

0

Input

]]

Output

Imposssible

题意

四种括号,离左括号(右括号)最近的右括号(左括号)恰是配对的就算完美了,若不是求最少改动几次,不能就输出Impossible

#include <stack>
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;

bool check_left(char ch)
{
    if(ch == '[' || ch == '<' || ch == '{' || ch == '(')
        return 1;
    else
        return 0;
}

bool couple(int a, int b)///char类型是特殊的int类型
{
    if(a == '[' && b == ']')
        return 1;
    if(a == '{' && b == '}')
        return 1;
    if(a == '(' && b == ')')
        return 1;
    if(a == '<' && b == '>')
        return 1;
    return 0;
}

int main()
{
    string s;
    cin >> s;
    int ans = 0;
    stack<char> st;
    for(int i = 0; i < s.length(); ++i)
    {
        if(check_left(s[i]))///如果是左括号,放入栈
            st.push(s[i]);
        else///如果是右括号
        {
            if(st.empty())///栈里没有左括号
            {
                cout << "Impossible" << '\n';
                return 0;
            }
            else
            {
                ///利用了栈的先进后出
                char last = st.top();///离此右括号最近的左括号
                st.pop();
                if(couple(last, s[i]))///匹配继续检测
                    continue;
                else
                    ans++;///不匹配就改动一次

            }
        }
    }
    if(!st.empty())///若还有左括号没匹配完
    {
        cout << "Impossible" << '\n';
        return 0;
    }
    else
        cout << ans << '\n';
    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy