hdu 6299 Balanced Sequence (贪心)

贪心要找一个贪心的方法,一般就是排个序,但是怎么排序呢,这里就是认为分成两种,l>r的和l

#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;
#define debug(x) std::cerr << #x << " = " << (x) << std::endl
typedef long long LL;
const int MAXN = 1e6 + 17;
const LL MOD = 1e9 + 7;
struct dap
{
    int l,r,id;
    dap(int a,int b,int c):l(a),r(b),id(c){}
    bool operator<(const dap & b) const
    {
        if(l>r&&b.l>b.r)
            return r<b.r;
        if(l>r&&b.l<=b.r)
            return true;
        if(l<=r&&b.l>b.r)
            return false;
        if(l<=r&&b.l<=b.r)
            return l>b.l;
    }
};
int main(int argc, char const* argv[])
{
#ifdef noob
    freopen("Input.txt", "r", stdin);
    freopen("Output.txt", "w", stdout);
#endif
    std::ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        vector<string > vec(n);
        for (int i = 0; i < n; ++i)
        {
            cin>>vec[i];
        }
        vector<dap > all;
        for (int i = 0; i < n; ++i)
        {
            string str = vec[i];
            stack<char > stk;
            int l = 0,r = 0;
            for (int j = 0; j < str.length(); ++j)
            {
                if(str[j]=='(')
                    stk.push('(');
                else if(!stk.empty()&&stk.top()=='(')
                    stk.pop();
                else
                    stk.push(')');
            }
            while(!stk.empty())
            {
                if(stk.top()=='(') l++;
                else r++;
                stk.pop();
            }
            all.push_back(dap(l,r,i));
        }
        sort(all.begin(), all.end());
        LL ans = 0;
        stack<char > stk;
        for (int i = 0; i < n; ++i)
        {
            string str = vec[all[i].id];
            for (int j = 0; j < str.length(); ++j)
            {
                if(str[j]=='(')
                    stk.push('(');
                else if(!stk.empty()&&stk.top()=='(')
                {
                    stk.pop();
                    ans+=2;
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37802215/article/details/81182527