4922: [Lydsy1706月赛]Karp-de-Chant Number 贪心+dp

原文链接:https://blog.csdn.net/qq_35541672/article/details/85256469

题解

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define M 340
using namespace std;

struct abcd
{
    int limit1,limit2,reward,length;
    friend bool operator < (const abcd &x,const abcd &y)
    {
        if(x.reward>=0 && y.reward<0)
            return true;
        if(x.reward<0 && y.reward>=0)
            return false;
        if(x.reward>=0 && y.reward>=0)
            return x.limit1<y.limit1;
        return x.limit2>y.limit2;
    }
}a[M];

int n,sum;
int f[M*M];
int main()
{
    char s[M];
    memset(f,0xef,sizeof f);
    f[0]=0;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x=0,y=0;
        scanf("%s",s);
        for(int j=0;s[j];j++)
        {
            if(s[j]=='(')
                y++;
            else
                y?y--:x++;
        }
        a[i].limit1=x;
        a[i].limit2=y;
        a[i].reward=y-x;
        a[i].length=strlen(s);
        sum+=y;
    }
    sort(a+1,a+n+1);

    //for(int i=1;i<=n;i++)
//      cout<<a[i].limit1<<' '<<a[i].limit2<<' '<<a[i].reward<<' '<<a[i].length<<endl;

    for(int i=1;i<=n;i++)
    {
        if(a[i].reward<0)
            for(int j=a[i].limit1;j<=sum;j++)
                f[j+a[i].reward]=max(f[j+a[i].reward],f[j]+a[i].length);
        else
            for(int j=sum;j>=a[i].limit1;j--)
                f[j+a[i].reward]=max(f[j+a[i].reward],f[j]+a[i].length);
    }
    cout<<f[0]<<endl;
    return 0;
}

 

上一篇:018-019 NET5_内置容器支持依赖注入+IServiceCollection的生命周期


下一篇:GAE&reward shaping