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);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/lgz0921/article/details/88919946