很简单的贪心,先按性价比排序,依次加上能afford的bean,直到room遍历完或者cat food用完了。。若只是cat food用完了,room还没遍历完,则加上剩下的cat food所能换取的bean。
AC代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_LEANGTH 1005 struct Room{ int bean; int catFood; double rate; }; int comp(const void *a, const void *b) { Room *ps1 = (Room *)a; Room *ps2 = (Room *)b; return ps2->rate - ps1->rate > 0 ? 1: -1; } int main() { int n,i,food; double res; Room *a = new Room[MAX_LEANGTH]; while(scanf("%d%d",&food,&n)!=EOF&&(food!=-1&&n!=-1)){ memset(a,0,sizeof(a)); for(i=0;i<n;i++) { scanf("%d%d",&a[i].bean,&a[i].catFood); a[i].rate=a[i].bean*1.0/a[i].catFood; } res=0.0; qsort(a,n,sizeof(a[0]),comp); for(i=0;i<n&&food>=a[i].catFood;i++){ res+=a[i].bean; food-=a[i].catFood; } if(i<n) res+=a[i].bean*food*1.0/a[i].catFood; printf("%.3lf\n",res); } return 0; }