HDU 6299 -- 贪心暴力

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6299
题意:() 这样子的是balanced,给你一些字符串,问你怎么样组合,使得balanced的长度最长
思路:先对每一个字符串删去(), (可以用stack来完成这一项工作), 删完之后剩下的字符串只有3种情况:全部(, 全部), 左右互背))((
然后就是根据( , )的多少及大小关系排序 ,排完之后再一次的判定即可
AC代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn=1e5+5;

struct node{
    int l,r;
}a[maxn];

char str[maxn];
int cmp(node a,node b)
{
    if( a.r >= a.l && b.r < b.l)
        return 0;
    if( a.r < a.l && b.r >= b.l)
        return 1;
    if( a.r>=a.l && b.r>=b.l)
        return  a.l > b.l;
    return a.r < b.r;
}
int main()
{
    int t,n;
    scanf("%d",&t);
    while (t--)
    {
        int ans = 0;
        scanf("%d",&n);
        for(int i = 1; i <= n; i++)
        {
            stack<char> S;
            while(!S.empty())S.pop();
            scanf("%s",str);
            int len = strlen(str);
            for(int j = 0; j < len; j++)
            {
                if(str[j]=='(')
                    S.push(str[j]);
                else
                {
                    if(!S.empty()&&S.top()=='(')
                        ans++,S.pop();
                    else
                        S.push(str[j]);
                }
            }

            int l = 0, r = 0;
            while(!S.empty())
            {
                if(S.top()==')')
                    r++;
                else
                    l++;
                S.pop();
            }
            a[i].l = l; a[i].r = r;
        }
        sort(a+1,a+n+1,cmp);
        int now = 0;
        for(int i = 1; i <= n; i++)
        {
            if( a[i].r > now)
            {
                a[i].r  = now;
            }
            ans += a[i].r;
            now -= a[i].r;
            now += a[i].l;
        }
        cout << ans*2 << '\n';
    }

    return 0;
}

这道题在判定balanced时,用string函数会出现问题,如下:

for(int i = 1; i < ss.length(); i++){
        if(ss[i] == ')' && ss[i-1] == '('){
                ans++;
                ss.erase(i-1, 2);
                i -= 2;
         }
}

说实话,string str[maxn],这东西有点奇怪,我在Debug中,str[i].length()不知为何有时会等于0,输出也是无,但是可以跑遍历!!??
这题被string函数卡了将近一天,但还是有问题,无奈…., AC代码是用别的判定方法做的

猜你喜欢

转载自blog.csdn.net/water_zero_saber/article/details/81289602