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个数,要求用最少的数字个数(注意:这m个数值可以重复使用),凑出n来。即:n=w1*a1+w2*a2+......+wn*an,就是求a1+a2+......+an最小~~~

题解:可以从上面的式子看出,是完全背包问题,但是由于n很大,不能直接用,所以用到有个名为鸽巢原理的东西,记住昂!!!数论知识,感觉记公式就挺好,会用,能解决这一类问题,就可以了,推倒过程不说了~~,代码里有,这个题用到的鸽巢原理写法~~上代码:

import java.util.*;
public class Main {
	static Scanner cin = new Scanner(System.in);
	static final int MAX = 10000;
	static final int inf = 0x3f3f3f3f;
	static int w [] = new int [MAX+200];
	static int dp [] = new int [MAX+200];
	public static void main(String[] args){
		int t=cin.nextInt();
		int n,m;
		while(t-->0) {
			m=cin.nextInt();n=cin.nextInt();
			for (int i = 1; i <= m;i++) {
				w[i]=cin.nextInt();
			}
			Arrays.sort(w, 1,m+1);
			int cnt=0;


			if(n>MAX) {//鸽巢原理~~
				int tt=(n-10000)%w[m]+MAX;
				cnt=(n-tt)/w[m];
				n=tt;
			}


			for (int i = 0; i < MAX+200;i++) dp[i]=inf;
			dp[0]=0;
			for (int i = 1; i <= m;i++) {//完全背包。。。
				for (int j = w[i]; j <= n;j++) {
					dp[j]=Math.min(dp[j], dp[j-w[i]]+1);
				}
			}
			if(dp[n]==inf) {
				System.out.println(-1);
				continue;
			}
			int ans=dp[n]+cnt;
			System.out.println(ans);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心脏dance

如果解决了您的疑惑,谢谢打赏呦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值