第一个使用贪心算法做的ACM题目O(∩_∩)O哈哈~。将兑换比从大到小排序,然后兑换直至完成,输出结果即可
View Code
1 #include2 #include 3 #include 4 struct Exchange{ 5 int room; 6 int javabean; 7 }; 8 int cmp( const void *a , const void *b ) 9 { 10 struct Exchange *c = (Exchange *)a; 11 struct Exchange *d = (Exchange *)b; 12 if (d->room*1.0/d->javabean > c->room*1.0/c->javabean) 13 return 1; 14 else if (d->room*1.0/d->javabean < c->room*1.0/c->javabean) 15 return -1; 16 else return 0; 17 } 18 double summation(Exchange* ex,int len,int javabeans) 19 { 20 double sum=0; 21 qsort(ex,len,sizeof(Exchange),cmp); 22 for(int i=0;i 0) 25 { 26 sum+=ex[i].room; 27 javabeans-=ex[i].javabean; 28 } 29 else 30 { 31 sum+=javabeans*1.0/ex[i].javabean*ex[i].room; 32 break; 33 } 34 } 35 return sum; 36 } 37 int main() 38 { 39 //freopen("FatNouseTrade.txt","r",stdin); 40 int m,n; 41 while(scanf("%d%d",&m,&n)!=EOF) 42 { 43 if(m==-1&&n==-1) 44 break; 45 Exchange* e=new Exchange[n]; 46 for(int i=0;i