FatMouse' Trade(水題,結構體排序,適合c初學者)
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
struct
food
{
int
x;
int
y;
double
z;
};
int
cmp(
const
void
*a,
const
void
*b)
{
return
(*(
struct
food *)b).z>(*(
struct
food*)a).z?1:-1;
}
int
main()
{
struct
food a[1100];
int
m,n,i;
double
s;
while
(1)
{
scanf
(
"%d%d"
,&m,&n);
if
(m==-1&&n==-1)
break
;
s=0;
for
(i=0;i<n;i++)
{
scanf
(
"%d%d"
,&a[i].x,&a[i].y);
a[i].z=a[i].x*1.0/a[i].y;
}
qsort
(a,n,
sizeof
(a[0]),cmp);
for
(i=0;i<n;i++)
{
if
(a[i].y<=m)
{
m-=a[i].y;
s+=a[i].x;
}
else
{
s+=m*a[i].z;
break
;
}
}
printf
(
"%.3lf\n"
,s);
}
return
0;
}
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define swap(a,b) (a=a+b,b=a-b,a=a-b)
#define maxn 320007
#define N 100000000
#define INF 0x3f3f3f3f
#define mod 1000000009
#define e 2.718281828459045
#define eps 1.0e18
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define memset(x,y) memset(x,y,sizeof(x))
#define Debug(x) cout<<x<<" "<<endl
#define lson i << 1,l,m
#define rson i << 1 | 1,m + 1,r
#define ll long long
using namespace std;
struct food
{
int x;
int y;
double z;
} a[1111];
bool cmp(struct food a,struct food b)
{
return a.z>b.z;
}
int main()
{
int m,n;
while(cin>>m>>n)
{
if(m==-1&&n==-1)
break;
for(int i=0; i<n; i++)
{
cin>>a[i].x>>a[i].y;
a[i].z=a[i].x*1.0/a[i].y;
}
sort(a,a+n,cmp);
double sum=0;
for(int i=0; i<n; i++)
if(m>=a[i].y)
{
m-=a[i].y;
sum+=a[i].x;
}
else
{
sum+=m*a[i].z;
break;
}
printf("%.3lf\n",sum);
}
return 0;
}