码迷,mamicode.com
首页 > 其他好文 > 详细

背包搜索--LH

时间:2017-10-09 22:51:41      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:++   ios   lld   ima   images   pac   ring   sort   algorithm   

技术分享

题解:搜索 meet in the middle

先搜一半,假设某个状态的体积是p,那么就要从另一半里找到体积小于

等于v-p 价值最大的状态。二分+前缀和。

代码:不会前缀和,暴力瞎写的。没有评测的地方..=^=

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long
using namespace std;

int an,bn,n,m,p,q,w[50],c[50];
LL ans;
struct WP{
    LL w,c;
    bool operator < (const WP &a) const{
      return w<a.w;
    }
}wp[1050000];


LL maxx(LL a,LL b){
    return a>=b?a:b;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d%d",&w[i],&c[i]);
    an=n/2;bn=n-an;
    for(int st=0;st<(1<<an);st++){
        p++;
        for(int i=0;i<an;i++){
            if((st>>i)&1){
                wp[p].w+=w[i+1];
                wp[p].c+=c[i+1];
            }
        }
    }
    sort(wp+1,wp+p+1);
    for(int st=0;st<(1<<bn);st++){
        WP all;all.w=0;all.c=0;//清为0 
        for(int i=0;i<bn;i++){
            if((st>>i)&1){
                all.w+=w[n-i];
                all.c+=c[n-i];
            }
        }
        WP gg;gg.w=m-all.w;gg.c=0;
        int cc=upper_bound(wp+1,wp+p+1,gg)-wp;
    //    cout<<all.w<<"  " <<gg.w<<"  "<<cc<<endl;
        for(int i=1;i<cc;i++)
            ans=maxx(ans,all.c+wp[i].c);
    }
    printf("%lld\n",ans);
    return 0;
}

 

背包搜索--LH

标签:++   ios   lld   ima   images   pac   ring   sort   algorithm   

原文地址:http://www.cnblogs.com/zzyh/p/7642757.html

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