• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ZOJ——2955 Interesting Dart Game (鸽巢原理)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
dart学习(六)之面向对象编程二发布时间:2022-07-13
下一篇:
JIT-动态编译与AOT-静态编译:java/ java/ JavaScript/Dart乱谈发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap