1. 程式人生 > >杭電acm 1009 FatMouse' Trade 比較典型的貪心問題

杭電acm 1009 FatMouse' Trade 比較典型的貪心問題

本題可以作為貪心問題的水題,我剛開始時,還掉以輕心,後第一遍wa後,我才發現這道題並不那麼簡單。

首先,分析該題:輸入後應先進行排序,按照j/f來進行排序。後再儘可能選取j/f比較大,直到m==0.

但是,問題到這並沒有結束,請你接下來試試這幾組資料:

0 1
1 0
1.000

1 0
0.000

5 4
10000 5
2000 2
100 0
300 0
10400.000
是不是wa了;

這才是本題問題所在。

後經過修改,原始碼如下:

#include <iostream>
#include <cstdio>

using namespace std;

typedef struct{
            double ans;
            int j;
            int f;
}ROOM;

ROOM room[1010];
int m,n;

int main(){
            while(scanf("%d%d",&m,&n)!=EOF&&(m!=-1||n!=-1)){
                        for(int i=0;i<n;i++){
                                    scanf("%d %d",&room[i].j,&room[i].f);
                                    room[i].ans =1.0* room[i].j/room[i].f;
                        }
                        for(int i=0;i<n-1;i++){
                                    for(int j=i+1;j<n;j++){
                                                if(room[j].ans>room[i].ans){
                                                            ROOM temp = room[i];
                                                            room[i] = room[j];
                                                            room[j] = temp;
                                                }
                                    }
                        }
                        int i=0;
                        double count=0;
                        for(int i=0;i<n;i++){
                                    if(room[i].f==0)        {
                                                            count+=room[i].j;
                                                            room[i].ans = 0;
                                                            room[i].f=0;
                                                            room[i].j=0;
                                    }
                        }
                        while(m){
                                    if(room[i].f<=m){
                                                count += room[i].j;
                                                m -= room[i].f;
                                                i++;
                                    }
                                    else{
                                                count += room[i].ans*m;
                                                break;
                                    }
                        }
                        if(n==0)    printf("0.000\n");
                        else printf("%.3f\n",count);
            }
            return 0;
}