Marbles

Marbles

时间: 1ms        内存:64M

描述:

I collect marbles (colorful small glass balls) and want to buy boxes to store them. The boxes come in two types:

Type 1:
each such box costs c1 dollars and can hold exactly n1 marbles
Type 2:
each such box costs c2 dollars and can hold exactly n2 marbles
I want each box to be filled to its capacity, and also to minimize the total cost of buying them. Help me find the best way to distribute my marbles among the boxes.

输入:

The input file may contain multiple test cases. Each test case begins with a line containing the integer n ( 1<=n<= 2,000,000,000). The second line contains c1 and n1, and the third line contains c2 and n2. Here, c1, c2, n1, and n2 are all positive integers having values smaller than 2,000,000,000. A test case containing a zero for the number of marbles terminates the input.

输出:

For each test case in the input print a line containing the minimum cost solution (two nonnegative integers m1 and m2, where mi = number of type i boxes required if one exists. Otherwise print ``failed''.
If a solution exists, you may assume that it is unique.

示例输入:

43
1 3
2 4
40
5 9
5 12
0

示例输出:

13 1
failed

提示:

参考答案(内存最优[800]):

#include<stdio.h>
int gcd(int a,int b)
{
	if(b==0) return a;
	return gcd(b,a%b);
}
int max(int a,int b)
{
	if(a>b) return gcd(a,b);
	return gcd(b,a);
}
int main()
{
	int v,c[2],n[2],i;
	while(scanf("%d",&v)==1&&v)
	{
		for(i=0;i<2;i++)
			scanf("%d%d",&c[i],&n[i]);
		int d=n[0]/max(n[0],n[1])*n[1];
		int max=v/n[0],sum=0,res=0,ra=0,rb=0;
		for(i=max;i>=0;)
			if((v-i*n[0])%n[1]==0)
			{
				sum=i*c[0]+(v-i*n[0])/n[1]*c[1];
				if(res==0||sum<res)
				{
					ra=i;
					rb=(v-i*n[0])/n[1];
					res=sum;
				}
				i-=d;
			}
			else
				i--;
		if(res)
			printf("%d %d\n",ra,rb);
		else
			printf("failed\n");
	}
	return 0;
}

参考答案(时间最优[0]):

#include<stdio.h>
int gcd(int a,int b)
{
	if(b==0) return a;
	return gcd(b,a%b);
}
int max(int a,int b)
{
	if(a>b) return gcd(a,b);
	return gcd(b,a);
}
int main()
{
	int v,c[2],n[2],i;
	while(scanf("%d",&v)==1&&v)
	{
		for(i=0;i<2;i++)
			scanf("%d%d",&c[i],&n[i]);
		int d=n[0]/max(n[0],n[1])*n[1];
		int max=v/n[0],sum=0,res=0,ra=0,rb=0;
		for(i=max;i>=0;)
			if((v-i*n[0])%n[1]==0)
			{
				sum=i*c[0]+(v-i*n[0])/n[1]*c[1];
				if(res==0||sum<res)
				{
					ra=i;
					rb=(v-i*n[0])/n[1];
					res=sum;
				}
				i-=d;
			}
			else
				i--;
		if(res)
			printf("%d %d\n",ra,rb);
		else
			printf("failed\n");
	}
	return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注