POJ 3991 Seinfeld

首先进行一次括号匹配,把正确匹配的全部删去。

删去之后剩下的状态肯定是 L个连续右括号+R个连续左括号。

如果L是偶数,答案是L/2+R/2;

否则答案是 (L-1)/2+(R-1)/2+2;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;

char s[2000 + 10];
char st[2000 + 10];
int top;

int main()
{
    int T = 1;
    while (~scanf("%s", s))
    {
        int ans = 0;
        memset(st, 0, sizeof st);
        top = -1;
        if (s[0] == '-') break;
        for (int i = 0; s[i]; i++)
        {
            if (top == -1) st[++top] = s[i];
            else
            {
                if (st[top] == '{'&&s[i] == '}')
                {
                    st[top] = 0;
                    top--;
                }
                else st[++top] = s[i];
            }
        }

        int L = 0, R = 0;
        for (int i = 0; st[i]; i++)
        {
            if (st[i] == '}') L++;
            else R++;
        }
        if (L % 2 == 0) ans = L / 2 + R / 2;
        else ans = (L - 1) / 2 + (R - 1) / 2 + 2;
        printf("%d. %d\n", T++, ans);
    }
    return 0;
}

 

posted @ 2016-03-07 08:27  Fighting_Heart  阅读(242)  评论(0编辑  收藏  举报