ZOJ-2955 Interesting Dart Game(鸽巢原理+完全背包)

Recently, Dearboy buys a dart for his dormitory, but neither Dearboy nor his roommate knows how to play it. So they decide to make a new rule in the dormitory, which goes as follows:

Given a number N, the person whose scores accumulate exactly to N by the fewest times wins the game.

Notice once the scores accumulate to more than N, one loses the game.

Now they want to know the fewest times to get the score N.

So the task is :
Given all possible dart scores that a player can get one time and N, you are required to calculate the fewest times to get the exact score N.

Input
Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 50) which is the number of test cases. And it will be followed by T consecutive test cases.

Each test case begins with two positive integers M(the number of all possible dart scores that a player can get one time) and N. Then the following M integers are the exact possible scores in the next line.

Notice: M (0 < M < 100), N (1 < N <= 1000000000), every possible score is (0, 100).

Output
For each test case, print out an integer representing the fewest times to get the exact score N.
If the score can’t be reached, just print -1 in a line.

Sample Input
3
3 6
1 2 3
3 12
5 1 4
1 3
2

Sample Output
2
3
-1

题意:给m件物品,用它们填起容量为n的背包,求物品件数的和最小。
N过大,考虑鸽巢原理。
推理:给n个整数a1,a2,a3…an,存在一段连续的区间,使区间和能够整除n。
证明:前缀和有(n+1)值,根据鸽巢原理,存在两个前缀和%n相等,即二者相减为0,故为这两个数之间的连续区间。

本题求a1* k1+a2* k2+a3* k3…an* kn==N.
所以k1+k2+k3…kn<an.(大于an必能用M* an代替,M为正整数)
N的最大值优化为an*an.
N的最大值为10000,先算10000以内的数,以外的用an填起来。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<list>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e4+5;
const int inf=0x3f3f3f3f;
int a[105],dp[N];
int main(){
	int T;
	scanf("%d",&T);
	while(T--){
	int V=10000;
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	sort(a+1,a+1+n);
	
	
	for(int i=1;i<=V;i++){
		dp[i]=inf;
	}
	dp[0]=0;
	int ans=inf;
	for(int i=1;i<n;i++){
		for(int j=a[i];j<=V;j++){
			dp[j]=min(dp[j],dp[j-a[i]]+1);
		}
	}
	

	for(int i=0;i<=V;i++){
		if(dp[i]!=inf&&(m-i)%a[n]==0){
			ans=min(ans,dp[i]+(m-i)/a[n]);
		}
	}
	if(ans==inf){
		printf("-1\n");
	}
	else printf("%d\n",ans);
}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值