D. Bracket Coloring

发布时间 2023-11-01 19:26:04作者: bhxyry

D. Bracket Coloring

题目大意:

给你一组括号序列,要求你将涂颜色括号分类,相同颜色为一组,每组括号按他们出现的顺序可以构成一个漂亮序列

如果满足以下条件之一,则括号序列称为优美序列:

  • 它是一个规则的括号序列;
  • 如果该序列中的字符顺序颠倒,它就会变成一个规则的括号序列。

思路:

首先左括号数应该等于右括号数,否则输出-1,如果本来就是一个完美序列一种颜色就够了,一般情况,按正序构成规则括号系列和反序的,只需两种颜色就可以把它分开了

code:

int n;
string s;
void solved()
{
    cin >> n;
    cin >> s;
    int num1 = count(s.begin(), s.end(), '(');
    int num2 = n - num1;
    if (num1 != num2)
    {
        cout << -1 << endl;
    }
    else
    {
        int tot = 0, op = 0, flag1 = 0, flag2 = 0;
        for (auto x : s)
        {
            if (x == '(')
            {
                tot++;
                op--;
                if (op < 0)
                    flag2 = 1;
            }
            else
            {
                tot--;
                op++;
                if (tot < 0)
                    flag1 = 1;
            }
        }
        if (flag1 == 0 || flag2 == 0)
        {
            cout << 1 << endl;
            for (int i = 0; i < n; ++i)
                cout << 1 << " ";
            cout << endl;
        }
        else
        {
            tot = 0;
            cout << 2 << endl;
            for (auto x : s)
            {
                if (x == '(')
                {
                    if (tot < 0)
                        cout << 1 << " ";
                    else
                        cout << 2 << " ";
                    tot++;
                }
                else
                {
                    tot--;
                    if (tot < 0)
                        cout << 1 << " ";
                    else
                        cout << 2 << " ";
                }
            }
            cout << endl;
        }
    }
}