码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3991 HDU3351 UVALive4733 Seinfeld【水题】

时间:2019-01-10 21:47:38      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:als   需要   \n   open   ati   none   bee   problem   sub   

Seinfeld
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 1551 Accepted: 722

Description

I’m out of stories. For years I’ve been writing stories, some rather silly, just to make simple problems look difficult and complex problems look easy. But, alas, not for this one.
You’re given a non empty string made in its entirety from opening and closing braces. Your task is to find the minimum number of “operations” needed to make the string stable. The definition for being stable is as follows:

An empty string is stable.

If S is stable, then {S} is also stable.

If S and T are both stable, then ST (the concatenation of the two) is also stable.

All of these strings are stable: {}, {}{}, and {{}{}}; But none of these: }{, {{}{, nor {}{.
The only operation allowed on the string is to replace an opening brace with a closing brace, or visa-versa.

Input

Your program will be tested on one or more data sets. Each data set is described on a single line. The line is a non-empty string of opening and closing braces and nothing else. No string has more than 2000 braces. All sequences are of even length.
The last line of the input is made of one or more ’-’ (minus signs.)

Output

For each test case, print the following line:

k. N
Where k is the test case number (starting at one,) and N is the minimum number of operations needed to convert the given string into a balanced one.

Sample Input

}{
{}{}{}
{{{}
---
Sample Output

  1. 2
  2. 0
  3. 1

Source

anarc 2009

问题链接POJ3991 HDU3351 UVALive4733 Seinfeld
问题简述:(略)
问题分析
????给定一个数量为偶数的括号字符串,问需要修改多少个括号才能使得括号匹配为合法。
????从左往右看,如果出现一个没有左括号与之匹配的右括号,那么它就一定需要修改为左括号。虽然说,匹配问题通常需要使用堆栈,其实这个题是不需要堆栈的,因为只有左右两种括号,做个统计匹配就可以了。最后剩下的没有匹配的左括号只需要修改其中的一半也就都匹配了。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C语言程序如下:

/* POJ3991 HDU3351 UVALive4733 Seinfeld */

#include <stdio.h>

#define N 2000
char s[N + 1];

int main(void)
{
    int caseno = 0, left, ans, i;
    while(~scanf("%s", s) && s[0] != '-') {
        ans = left = 0;
        for(i = 0; s[i]; i++) {
            if(s[i] == '{')
                left++;
            else {
                if(left > 0)
                    left--;
                else
                    ans++, left = 1;
            }
        }
        ans += left / 2;

        printf("%d. %d\n", ++caseno, ans);
    }

    return 0;
}

POJ3991 HDU3351 UVALive4733 Seinfeld【水题】

标签:als   需要   \n   open   ati   none   bee   problem   sub   

原文地址:https://www.cnblogs.com/tigerisland45/p/10252276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!