CH2401 送礼物(双向dfs)

CH2401 送礼物

描述

作为惩罚,GY被遣送去帮助某神牛给女生送礼物(GY:貌似是个好差事)但是在GY看到礼物之后,他就不这么认为了。某神牛有N个礼物,且异常沉重,但是GY的力气也异常的大(-_-b),他一次可以搬动重量和在w(w<=2^31-1)以下的任意多个物品。GY希望一次搬掉尽量重的一些物品,请你告诉他在他的力气范围内一次性能搬动的最大重量是多少。

输入格式

第一行两个整数,分别代表W和N。
以后N行,每行一个正整数表示G[i],G[i]<= 2^31-1。

输出格式

仅一个整数,表示GY在他的力气范围内一次性能搬动的最大重量。

样例输入

20 5
7
5
4
18
1

样例输出

19

数据范围与约定

    • 对于20%的数据 N<=26
      对于40%的数据 W<=2^26
      对于100%的数据 N<=45 W<=2^31-1
  • 1. 将礼物分成两半,首先在前一半中暴力搜索出所有情况,记录,排序,去重,然后搜后一半礼物,对于后一半每一个可以达到的重量值t,都在前一半搜过的情况中二分查找W-t中数值最大的,然后更新答案,
  • 2. 优化搜索顺序,将礼物重量降序排列后再分半,搜索
  • 3. 选取适当的折半划分点,据lyd大佬所说,在N/2+2处搜索速度最快

代码:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cctype>
 5 #include <cmath>
 6 using namespace std;
 7 
 8 inline long long read()
 9 {
10     long long x(0),f(1); char ch;
11     while(!isdigit(ch=getchar())) if(ch=='-') f=-1;
12     while(isdigit(ch)) x=x*10+ch-'0',ch=getchar();
13     return f*x;
14 }
15 #define res register int
16 int g[50],n,half,tot;
17 unsigned int a[20000000],W,ans;
18 
19 #define max(a,b) (a>b?a:b)
20 
21 void dfs1(int x,unsigned int sum)
22 {
23     if(x==half) {
24         a[++tot]=sum; return ;
25     }
26     dfs1(x+1,sum);
27     if(sum+g[x]<=W) dfs1(x+1,sum+g[x]);
28 }
29 
30 inline void calc(unsigned int val)
31 {
32     unsigned int rest=W-val;
33     int l=1,r=tot;
34     while(l<r)
35     {
36         int mid=(l+r+1)>>1;
37         if(a[mid]<=rest) l=mid;
38         else r=mid-1;
39     }
40     ans=max(ans,val+a[l]);
41 }
42 
43 void dfs2(int x,unsigned int sum)
44 {
45     if(x==n+1) {
46         calc(sum); 
47         return;
48     }
49     dfs2(x+1,sum);
50     if(sum+g[x]<=W) dfs2(x+1,sum+g[x]);
51     
52 }
53 
54 int main()
55 {
56 //    W=read(); n=read(); 
57     cin>>W>>n;
58     for(res i=1 ; i<=n ; i++) scanf("%d",&g[i]);//g[i]=read();
59     sort(g+1,g+n+1); 
60     reverse(g+1,g+n+1);
61     half=n/2+3;
62     dfs1(1,0);
63     sort(a+1,a+tot+1);
64     tot=unique(a+1,a+tot+1)-a-1;
65     dfs2(half,0);
66     printf("%lld\n",ans);
67     return 0;
68 }
View Code

猜你喜欢

转载自www.cnblogs.com/wmq12138/p/10386678.html