• 01背包排序


    https://vjudge.net/contest/150953#problem/D

    此题关键 就是排序,刚开始按q排序结果想死都想不出来应该是q-p排

    一维的dp

    #include<map>
    #include<set>
    #include<list>
    #include<cmath>
    #include<queue>
    #include<stack>
    #include<vector>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #define ll long long
    
    using namespace std;
    
    const int maxn=505,N=5005;
    int dp[N];
    struct edge{
        int p,q,v,c;
    }e[maxn];
    int comp(const edge &a,const edge &b)
    {
        return a.c<b.c;
    }
    int main()
    {
        int t,n,W;
        while(~scanf("%d%d",&n,&W)){
            memset(dp,0,sizeof(dp));
            for(int i=0;i<n;i++)
            {
                cin>>e[i].p>>e[i].q>>e[i].v;
                e[i].c=e[i].q-e[i].p;
            }
            sort(e,e+n,comp);
            for(int i=0;i<n;i++)
                for(int j=W;j>=e[i].q;j--)
                {
                    dp[j]=max(dp[j],dp[j-e[i].p]+e[i].v);
                }
            cout<<dp[W]<<endl;
        }
        return 0;
    }

    二维的dp

    #include<map>
    #include<set>
    #include<list>
    #include<cmath>
    #include<queue>
    #include<stack>
    #include<vector>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #define ll long long
    
    using namespace std;
    
    const int maxn=505,N=5005;
    int dp[maxn][N];
    struct edge{
        int p,q,v,c;
    }e[maxn];
    int comp(const edge &a,const edge &b)
    {
        return a.c<b.c;
    }
    int main()
    {
        int t,n,W;
        while(~scanf("%d%d",&n,&W)){
            memset(dp,0,sizeof(dp));
            for(int i=0;i<n;i++)
            {
                cin>>e[i].p>>e[i].q>>e[i].v;
                e[i].c=e[i].q-e[i].p;
            }
            sort(e,e+n,comp);
            for(int i=0;i<n;i++)
                for(int j=W;j>=0;j--)
                {
                    if(j>=e[i].q)dp[i+1][j]=max(dp[i][j],dp[i][j-e[i].p]+e[i].v);
                    else dp[i+1][j]=dp[i][j];
                }
            cout<<dp[n][W]<<endl;
        }
        return 0;
    }
    /*
    2 10
    10 15 10
    5 10 5
    3 10
    5 10 5
    3 5 6
    2 7 3
    5
    11
    */
  • 相关阅读:
    转义将正文中换行符
    THINKPHP短链接设置方法(路由设置)
    MEMCACHE分布式算法(PHP)
    win7下memCache安装过程
    JQUERY根据值将input控件选中!
    Thinkphp CURD中的where方法
    SQL语法LPAD和RPAD
    Linux查看docker容器日志
    Linux中清空docker容器日志
    错误记录——fail: Microsoft.AspNetCore.Server.Kestrel[13]
  • 原文地址:https://www.cnblogs.com/acjiumeng/p/6537637.html
Copyright © 2020-2023  润新知