算法1——Mouse' Trade

Problem Description:

Mouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, Bean.The warehouse has N rooms. The i-th room contains J[i] pounds of Beans and requires F[i] pounds of cat food. Mouse does not have to trade for all the Beans in the room, instead, he may get J[i]* a% pounds of Beans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of Beans he can obtain.

老鼠准备了M英镑的猫食,准备去和监管仓库的猫去交换里面它最喜欢的食物豆子。仓库里有N间房子,第i间房子中有J[i]英镑的豆子并且需要F[i]英镑的猫食交换。老鼠不需要拿走房间中全部的豆子,相反他可以通过支付F[i]*%a英镑的猫食得到J[i]*%a英镑的豆子。这儿a是一个数字,你需要解决的是告诉它可以得到的最大数量的豆子。

Input:

The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.

输入由多个测试案例组成,每个案例开始于包含两个非负整数M和N的一行,然后下面有N行,每一行分别包含两个非负整数J[i]和F[i],在最后一个测试案例之后以两个-1作为结束标志,且所有的整数都不大于1000.

Output:

For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of Beans that Mouse can obtain.


Sample Input
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1


Sample Output
13.333

31.500

代码如下:

/*注意快速排序函数qsort*/
//功 能: 快速排序
//头文件:stdlib.h
//用 法: void qsort(void *base,int nelem,int width,int (*fcmp)(const void *,const void *));
//参数: 
//1 待排序数组首元素的地址 
//2 数组中待排序元素数量
//3 各元素的占用空间大小
//4 指向函数的指针,用于确定排序的顺序
#include<stdio.h>
#include<stdlib.h>
typedef struct trade_s
{
	int bean,food;
	double normalize;
}trade_t;
static trade_t w[1100];
int cmp(const void*x,const void *y)	//此处函数为递增快速排序
{									//此处const关键字是指const常量,具有不可变性
	return((trade_t*)x)->normalize-((trade_t*)y)->normalize>0?-1:1;
}
int main()
{
	int m,n,i;
	double sum;
	while(scanf("%d%d",&m,&n))
	{
		if(m==-1&&n==-1)
			break;
		sum=0;
		for(i=0;i<n;i++) 
		{
		scanf("%d%d",&w[i].bean,&w[i].food);
		w[i].normalize=((double)w[i].bean)/w[i].food;
		}
		qsort(w,n,sizeof(trade_t),cmp);
		for(i=0;i<n;i++)
			if(m>=w[i].food)
			{
				printf("food %d %d\n",w[i].food,w[i].bean);
				sum+=w[i].bean;
				m-=w[i].food;
			}
			else
			{
				sum+=w[i].normalize*m;
				break;
			}
			printf("%.3lf\n",sum);
	}
	return 0;
}

//本篇文章来源于微信公众号ACM算法日常,是对其中文章的学习之后所写,已获授权

//原博文地址:

https://mp.weixin.qq.com/s/cflAqrTM-4BBc4crPULrnQ 点击打开链接




猜你喜欢

转载自blog.csdn.net/qq_41345173/article/details/80699570