4800: [Ceoi2015]Ice Hockey World Championship
Time Limit: 10 Sec Memory Limit: 256 MB
Submit: 482 Solved: 257
[Submit][Status][Discuss]
Description
有n个物品,m块钱,给定每个物品的价格,求买物品的方案数。
Input
第一行两个数n,m代表物品数量及钱数
第二行n个数,代表每个物品的价格
n<=40,m<=10^18
Output
一行一个数表示购买的方案数
(想怎么买就怎么买,当然不买也算一种)
Sample Input
5 1000
100 1500 500 500 1000
Sample Output
8
HINT
Source
题解:第一道双向搜索的题。。
如果直接搜索的话,稳T,稳到不行,考虑双向搜索。先将物品折半,将前一半可以凑到的钱数存起来,后一半同理。
枚举前一半,在后一半里查找刚好不会超过钱数的个数,然后加起来。
自己随便口胡一下。。双向搜索大概就是一半枚举,一半查询?
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 40 + 5;
const int M = 2000000 + 10;
int n;
ll m,a[N],a1[M],a2[M];
int ed,cnt1=0,cnt2=0;
void dfs(int x,int ed,ll sum,ll *ar,int &cnt){
if(sum>m) return ;
if(x>ed){
ar[++cnt]=sum;
return ;
}
dfs(x+1,ed,sum+a[x],ar,cnt);
dfs(x+1,ed,sum,ar,cnt);
}
int main(){
// freopen("data.in","r",stdin);
scanf("%d%lld",&n,&m);
for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
ed=n>>1;
dfs(1,ed,0,a1,cnt1);
dfs(ed+1,n,0,a2,cnt2);
sort(a1+1,a1+cnt1+1);sort(a2+1,a2+cnt2+1);
ll ans=0;
for(int i=1;i<=cnt1;++i){
if(a1[i]+a2[1]>m) break;
ans+=upper_bound(a2+1,a2+cnt2+1,m-a1[i])-a2-1;
}
cout<<ans<<endl;
return 0;
}