码迷,mamicode.com
首页 > 编程语言 > 详细

01背包排序

时间:2017-03-12 14:57:30      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:efi   bsp   fine   com   lis   math   struct   for   test   

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
*/

 

01背包排序

标签:efi   bsp   fine   com   lis   math   struct   for   test   

原文地址:http://www.cnblogs.com/acjiumeng/p/6537637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!