poj 1855:Mint 搜索

1855:Mint

總時間限制: 

3000ms 

內存限制: 

65536kB

描述

The Royal Canadian Mint has commissioned a new series of designer coffee tables, with legs that are constructed from stacks of coins. Each table has four legs, each of which uses a different type of coin. For example, one leg might be a stack of quarters, another nickels, another loonies, and another twonies. Each leg must be exactly the same length. 
Many coins are available for these tables, including foreign and special commemorative coins. Given an inventory of available coins and a desired table height, compute the lengths nearest to the desired height for which four legs of equal length may be constructed using a different coin for each leg. 

輸入

Input consists of several test cases. Each case begins with two integers: 4 <= n <= 50 giving the number of types of coins available, and 1 <= t <= 10 giving the number of tables to be designed. n lines follow; each gives the thickness of a coin in hundredths of millimetres. t lines follow; each gives the height of a table to be designed (also in hundredths of millimetres). A line containing 0 0 follows the last test case.

輸出

For each table, output a line with two integers: the greatest leg length not exceeding the desired length, and the smallest leg length not less than the desired length.

樣例輸入

4 2
50
100
200
400
1000
2000
0 0

樣例輸出

800 1200
2000 2000

來源

Waterloo local 2004.09.19

#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
using namespace std;
int n,t,h,Max,Min;
int Coin[55];
int gcd(int a,int b)
{
	if(b==0)return a;
	else return gcd(b,a%b);
}
int lcm(int a,int b)
{
	return a/gcd(a,b)*b;
}
void dfs(int H,int num,int cur)//當前湊出高度爲H,湊出了num只腳,目前搜索到第cur種硬幣 
{
	if(num==4)
	{
		int tmp=h/H*H;
		if(tmp==h)
		{
			Max=Min=tmp;
		}
		else
		{
			if(Max==-1||Max<tmp)
				Max=tmp;
			if(Min==-1||Min>tmp+H)
				Min=tmp+H;
		}
		return;
	}
	if(cur==n)return;
	dfs(H,num,cur+1);
	int l;
	if(H==0)l=Coin[cur];
	else l=lcm(H,Coin[cur]);
	dfs(l,num+1,cur+1);
}
int main()
{
	while(cin>>n>>t)
	{ 
		if(n==0&&t==0)break;
		for(int i=0;i<n;++i)
		{
			cin>>Coin[i];
		}
		for(int i=0;i<t;++i) 
		{
			cin>>h;
			Max=-1;Min=-1;
			dfs(0,0,0);
			cout<<Max<<" "<<Min<<endl;
		}
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章