HDU 3351

http://acm.hdu.edu.cn/showproblem.php?pid=3351

乍一看很像经典的括号匹配问题,其实不然,因为操作并非增加括号,而是翻转括号

只需记录多余的左括号的数量即可,遇到右括号就减去,左括号数量不足就翻转,最后剩余的左括号一半是需要翻转的(转成右括号)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <map>

using namespace std;

char s[2005];

int main() {
    int cas = 1;
    while(~scanf("%s", s) ) {
        if(s[0] == '-') break;
        int len = strlen(s);
        int cnt = 0;
        int ans = 0;
        for(int i = 0; i < len; i++){
            if(s[i] == '{') cnt++;
            else{
                if(cnt > 0){
                    cnt--;
                }
                else{
                    ans++;
                    cnt++;
                }
            }
        }
        if(cnt > 0) ans += cnt / 2;
        printf("%d. %d
", cas++, ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/xiaohongmao/p/4105034.html