Interesting Dart Game ZOJ - 2955

6 篇文章 0 订阅

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的背包,这m个数每个数都可以一直重复使用,问放满这个背包最少需要多少个数?

 

思路:这个题就是个价值为1的完全背包,但是n非常大,数组是开不下的,因此需要对这个n进行优化。

用到了鸽笼原理的结论:设可选的 N 个数从小到大依次为 a(1)、 a(2) … a(N),则在最优的取法中,小于 a(N) 的数不会多于 a(N) 个。即 选用 小于a(N) 的数字超过 a(N)个 ,那就会出现这些选取的数某个子集是a(N)的倍数,那么放a(N)一定要比放那个子集中的数要少。

那么当n>10000(因为maxM*maxscore==10000)时,我们可以一直放maxcost,直到放到当前背包容量小于10000,我们就可以用最普通的完全背包求解了。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10109;
const int inf=0x3f3f3f3f;
int maxx=10000;
int cost[maxn],dp[maxn];
int main()
{
	int t,n,m;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&m,&n);
		for(int i=1;i<=m;i++)
			scanf("%d",&cost[i]);
		sort(cost+1,cost+1+m);
		int num=0;
		if(n>maxx)
		{
			int tmp=(n-maxx)%cost[m]+maxx;
			num=(n-tmp)/cost[m];
			n=tmp;
		}
		memset(dp,inf,sizeof(dp));
		dp[0]=0;
		for(int i=1;i<=m;i++)
			for(int j=cost[i];j<=n;j++)
				dp[j]=min(dp[j],dp[j-cost[i]]+1);
		if(dp[n]==inf)
			printf("-1\n");
		else
			printf("%d\n",dp[n]+num);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值