最基本的贪心,此题主要用到了sort排序。 #include <stdio.h> #include<iostream> #include<algorithm> using namespace std; const int MAXN=1000; struct Rooms { int j,f; double rate; }a[MAXN+1]; int cmp( Rooms p, Rooms q) { return p.rate > q.rate; } int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int M,N; while(scanf("%d%d",&M, &N),M!=-1 || N != -1) { for(int i=0; i < N; i++) { scanf("%d%d",&a[i].j,&a[i].f); a[i].rate = (a[i].j * 1.0)/ a[i].f; } sort(a,a+N,cmp); double sum ,tot; sum = tot =0; for(int i=0; i < N; i++) { sum += a[i].j; tot += a[i].f; if(tot == M) break; if(tot > M) { tot -= a[i].f; sum -= a[i].j; sum += (((M-tot)*1.0/a[i].f)*a[i].j); break; } } printf("%.3lf/n",sum); } return 0; }