pipioj 1241: 01背包(中途相遇法)

 1 #define bug(x) cout<<#x<<" is "<<x<<endl
 2 #define IO std::ios::sync_with_stdio(0)
 3 #include <bits/stdc++.h>
 4 using namespace  std;
 5 typedef long long ll;
 6 #define mk make_pair
 7 #define pb push_back
 8 const int inf=2147483647;
 9 const int N=1e5+10;
10 ll w,ans;
11 ll a[N],v[N];
12 int cnt,n,e;
13 void dfs(int h,ll x){
14     if(h>e){
15         a[++cnt]=x;
16         return;
17     }
18     dfs(h+1,x);
19     dfs(h+1,x+v[h]);
20 }
21 void dfs1(int h,ll x){
22     if(h>e){
23         int k=upper_bound(a+1,a+1+cnt,w-x)-a;
24         ans+=k-1;
25         return;
26     }
27     dfs1(h+1,x);
28     dfs1(h+1,x+v[h]);
29 }
30 int main(){
31     IO;
32     while(cin>>n>>w){
33         for(int i=1;i<=n;i++){
34             cin>>v[i];
35         }
36         ans=cnt=0;
37         e=n/2;
38         dfs(1,0);
39         sort(a+1,a+1+cnt);
40         e=n;
41         dfs1(n/2+1,0);
42         cout<<ans<<endl;
43     }
44 }
45 /*
46 30 100
47 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
48 
49 */
原文地址:https://www.cnblogs.com/ccsu-kid/p/14224185.html