Description
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
Output
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
sort函数要和using namespace std;和头文件联合使用。
贪心的思路。对当前的数据进行排序,然后依次对最大的或者最小的进行操作。
第二周培训A题,很简单。但是runtime error。
runtime error代码
#include <stdio.h>
#include <string.h>
int main()
{
static double M,N,J[101],F[100];
while(scanf("%lf %lf",&M,&N) != EOF)
{
if(M == -1&&N == -1) break;
else
{
double ans = 0;
double JS[101];
for(int i = 0;i < N;i++)
{
scanf("%lf %lf",&J[i],&F[i]);
JS[i] = J[i]/F[i];
}
//for(int i = 0;i<N;i++)printf("%lf\n",JS[i]);
double max;
int Imax;
max = JS[0];Imax=0;
for(int i = 0;i<N;i++)
{
if(JS[i]>max)
{
max = JS[i];
Imax = i;
}
}
while(M>F[Imax])
{
ans += J[Imax];
M =M - F[Imax];
JS[Imax] = 0;
max = 0;
for(int i = 0;i<N;i++)
{
if(JS[i]>max)
{
max = JS[i];
Imax = i;
}
}
//printf("%lf %d\n",max,Imax);
//printf("%.3lf\n",ans);
}
ans += M*JS[Imax];
printf("%.3lf\n",ans);
}
}
return 0;
}
AC代码(拷的)
- #include <iostream>
- #include <cstdio>
- #include <algorithm>
- using namespace std;
- const int maxn = 10005;
- struct W {
- double get;//收入
- double pay;//付出的猫食
- double ave;//收入/付出比
- } w[maxn];
- bool cmp(W a, W b) {
- if (a.ave > b.ave) {
- return true;
- }
- return false;
- }
- int main() {
- int n;
- double m;
- while (scanf("%lf%d", &m, &n), n != -1 && m != -1) {
- int i;
- for (i = 0; i < n; ++i) {
- scanf("%lf %lf", &w[i].get, &w[i].pay);
- w[i].ave = w[i].get / w[i].pay;
- }
- sort(w, w + n, cmp);//贪心,对w按照get/pay进行降序排序
- double sum = 0;
- i = 0;
- // while(m >= 0){//不知道为什么这种写法就是不行.
- // if (m >= w[i].pay) {
- // sum = sum + w[i].get;
- // m = m - w[i].pay;
- // } else {
- // sum = sum + w[i].ave * m;
- // break;
- // }
- // i++;
- // }
- for (i = 0; i <= n - 1; i++) {
- if (m >= w[i].pay) {//如果当前剩余的猫食还足够的话
- sum = sum + w[i].get;//那就把那个房间的粮食全部买下
- m = m - w[i].pay;//并且手上见去相应的猫食
- } else {//如果现在手上的猫食已经不够
- sum = sum + w[i].ave * m;//那么就按比例拿去一定的猫食
- break;
- }
- }
- printf("%.3lf\n", sum);
- }
- return 0;
- }