时间: 1000ms / 空间: 131072KiB / Java类名: Main
描述
作为惩罚,GY被遣送去帮助某神牛给女生送礼物(GY:貌似是个好差事)但是在GY看到礼物之后,他就不这么认为了。某神牛有N个礼物,且异常沉重,但是GY的力气也异常的大(-_-b),他一次可以搬动重量和在w(w<=2^31-1)以下的任意多个物品。GY希望一次搬掉尽量重的一些物品,请你告诉他在他的力气范围内一次性能搬动的最大重量是多少。
输入格式
第一行两个整数,分别代表W和N。
以后N行,每行一个正整数表示G[i],G[i]<= 2^31-1。
以后N行,每行一个正整数表示G[i],G[i]<= 2^31-1。
输出格式
仅一个整数,表示GY在他的力气范围内一次性能搬动的最大重量。
测试样例1
输入
输出
备注
对于20%的数据 N<=26
对于40%的数据 W<=2^26
对于100%的数据 N<=45 W<=2^31-1
对于40%的数据 W<=2^26
对于100%的数据 N<=45 W<=2^31-1
折半DFS。先DFS前一半物品,枚举每个物品拿或不拿,再DFS后一半物品,与之前算到的结果匹配。
堆了各种细节优化,还是有一个点1200ms……
最后加了个玄学卡时优化,过了。总计提交7次,中间评测机抽风3次,这题神TM鬼畜。
/*by SilverN*/
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define HK_Reporter main
using namespace std;
const int mxn=;
LL read(){
LL x=,f=; char ch=getchar();
while(ch<'' || ch>'')ch=getchar();
if(ch=='-'){f=-;ch=getchar();}
while(ch>='' && ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
int n;
LL w;
LL a[mxn];
LL res[],cnt;
int find(LL x){
int l=,r=cnt;
int mid;
while(l<=r){
mid=(l+r)>>;
if(res[mid]<x)l=mid+;
else if(res[mid]>x) r=mid-;
}
return l-;
}
LL ans=;int mid;
int bignews=;
void dfs(int now,int limit,LL wt){
bignews++;
if(bignews>){
printf("%lld\n",ans);
exit();
}
if(now>limit){
if(limit==mid){
res[++cnt]=wt;
return;
}
int tmp=find(w-wt);
ans=max(ans,wt+res[tmp]);
return;
}
dfs(now+,limit,wt);//不选
if(wt+a[now]<=w)dfs(now+,limit,wt+a[now]);//选
return;
}
int HK_Reporter(){
w=read();n=read();
int i,j;
for(i=;i<=n;i++){
a[i]=read();
}
mid=n/;
dfs(,mid,);
sort(res+,res+cnt+);
dfs(mid+,n,);
printf("%lld\n",ans);
return ;
}