BZOJ4922: [Lydsy 1706] Karp-de-Chant Number (DP)

Keywords: PHP less

Portal

Explanation:
It's a wonderful question.

If'('as 1,') is regarded as - 1, then the only useful things for a parentheses sequence are the prefix min, the suffix max, and sum.

Considering a legitimate bracket sequence, it is still legitimate to sort the parts whose size is greater than 0 according to the prefix max from small to large, and the parts whose size is less than 0 according to the suffix min from large to small. Then we can just enumerate the bracket sequence to DP in this order.

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

const int N=300*301;
struct data {
    int lim,det,len;
    data(int lim,int det,int len) : lim(lim),det(det),len(len) {}
};
list <data> q;
typedef list <data> ::iterator it;

int n,mx,f[N];
char ch[N];

int main() {
    memset(f,-1,sizeof(f));
    scanf("%d",&n);
    for(int i=1;i<=n;i++) {
        scanf("%s",ch+1);
        int len=strlen(ch+1),mn=1e9,s=0;
        for(int j=1;j<=len;j++) {
            if(ch[j]=='(') ++s;
            else --s;
            mn=min(mn,s);
        } 
        q.push_back(data(-mn,s,len));
    } 
    mx=0; f[0]=0;
    while(1) {
        int cnt=0,v=-1e9;
        it pos;
        for(it i=q.begin();i!=q.end();i++) 
            if(i->lim<=mx && i->det+i->lim>v) v=i->det+i->lim, pos=i, cnt++;
        v=1e9;
        for(it i=q.begin();i!=q.end();i++) 
            if(i->lim<=mx && i->det>=0 && i->lim<v) v=i->lim, pos=i, cnt++;
        if(!cnt) break;
        if(pos->det>0) {
            for(int i=mx;i>=pos->lim && i>=0;i--) 
                if(~f[i]) f[i+pos->det]=max(f[i+pos->det],f[i]+pos->len);
            mx+=pos->det;
        } else {
            for(int i=pos->lim;i<=mx;i++)
                if(~f[i]) f[i+pos->det]=max(f[i+pos->det],f[i]+pos->len);
        } q.erase(pos);
    } 
    cout<<f[0]<<'\n';
}

Posted by damisi on Sun, 03 Feb 2019 18:21:15 -0800