lightoj 1127 Funny Knapsack

1127 - Funny Knapsack

Given n integers and a knapsack of weight W,you have to count the number of combinations for which you can add the items inthe knapsack without overflowing the weight.

Input

Input starts with an integer T (≤ 100),denoting the number of test cases.

Each case contains two integers n (1 ≤ n ≤30) and W (1 ≤ W ≤ 2 * 109) and the next linewill containn integers separated by spaces. The integers will be nonnegative and less than109.

Output

For each set of input, print the case number and the numberof possible combinations.

Sample input

3

1 1

1

1 1

2

3 10

1 2 4

Sample Output


Case 1: 2

Case 2: 1

Case 3: 8


有n(<=30)个整数和一个数W(<=2e9)。问每个数之多用一次并且总和不超过W的情况下有多少种组合数。

所有的情况有2^30种,必然TLE。

将n个数分成两份,在每一份里面统计用这些数能组成多少种整数。然后两种一综合就是答案。


ll a[maxn];
ll b[maxn];
ll t[maxn];
int main(){
	int T;

	cin>>T;
	for(int tt=1;tt<=T;tt++){
		memset(t,0,sizeof(t));
		memset(a,0,sizeof(a));
		memset(b,0,sizeof(b));
		int n;
		ll w;
		scanf("%d%lld",&n,&w);
		int ta=n>>1;
		int tb=n-ta;
		int l=1<<ta;
		int r=1<<tb;
		for(int i=0;i<n;i++)
			scanf("%lld",&t[i]);

		for(int i=0;i<l;i++){
			for(int j=0;j<ta;j++){
				if(i&(1<<j))
					a[i]+=t[j];
			}
		}
		for(int i=0;i<r;i++){
			for(int j=0;j<tb;j++){
				if(i&(1<<j))
					b[i]+=t[ta+j];
			}
		}
		ll ans=0;
		sort(b,b+r);
		for(int i=0;i<l;i++){
			if(w-a[i]>=0){
				ans+=upper_bound(b,b+r,w-a[i])-b;
			}
		}
		printf("Case %d: %lld\n",tt,ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值