2015-基础(3)

C - C

Greedy Mouse

Description

FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean. 
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans 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 JavaBeans he can obtain. 
 

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. 
 

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 JavaBeans that FatMouse 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
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
int a[5000],b[5000];
int main()
{
	int t,n,i,j;
	double c[5000],k,sum;
	while(cin >> t >> n)
	{
		sum=0;
		if(t==-1&&n==-1)
		{
			break;
		}
		for(i=0;i<n;i++)
		{
			cin >> a[i] >> b[i];
			c[i]=a[i]*1.0/b[i];
		}
		for(i=0;i<n-1;i++)
		{
			for(j=i+1;j<n;j++)
			{
				if(c[i]<c[j])
				{
					k=c[i];
					c[i]=c[j];
					c[j]=k;
					k=b[i];
					b[i]=b[j];
					b[j]=k;
					k=a[i];
					a[i]=a[j];
					a[j]=k;
				}
			}
		}
		for(i=0;i<n;i++)
		{
			if(b[i]<t)
			{
				sum+=a[i];
				t-=b[i];
				c[i]=0;
			}
			else
			{
				sum+=t*1.0*c[i];
				break;
			}
		}
		cout << setiosflags(ios::fixed) << setprecision(3) << sum << endl;
	}
	return 0;
}


相隔了差不多两个月又重新做了一次,相比之前的简单了一点。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct S 
{
	int L;
	int R;
	double avg;
}a[210];
bool cmp(const S& p,const S&q)
{
	return p.avg>q.avg;
}
int main()
{
	int n,m,i;
	double sum;
	while (~scanf("%d %d",&n,&m))
	{
		if (n==-1&&m==-1)
		{
			break;
		}
		for (i=0;i<m;++i)
		{
			scanf("%d %d",&a[i].L,&a[i].R);
			a[i].avg=a[i].L*1.0/a[i].R;
		}
		sort(a,a+m,cmp);
		for (i=0,sum=0;i<m&&n;++i)
		{
			
			if (n>=a[i].R)
			{
				n-=a[i].R;
				sum+=a[i].L;
			}
			else
			{
				sum+=n*a[i].avg;
				break;
			}
		}
		printf("%.3f\n",sum);
	}
	return 0;
}


你可能感兴趣的:(ACM)