在做hdoj的1009,本来这道题目不是很难,可是对于struct动态数组操作不是很熟,做了很久,在这里记录一下,避免下次继续出错。
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25384 Accepted Submission(s): 8029
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
13.333 31.500
代码如下:
#include<stdio.h> #include<algorithm> using namespace std; struct trade{ int j; int f; }; bool compare(const trade &a, const trade &b){ return double(a.j)/double(a.f)>double(b.j)/double(b.f); } void main(){ int m,n; double sum; while(1){ sum=0.0; scanf("%d %d",&m,&n); if(m==-1) break; trade* array=new trade[n]; for(int i=0; i<n; i++){ scanf("%d %d",&array[i].j,&array[i].f); } sort(array,array+n,compare); for(int j=0; j<n; j++){ if(m<array[j].f){ sum+=double(array[j].j)/double(array[j].f)*m; break; } m-=array[j].f; sum+=array[j].j; } printf("%.3f\n",sum); delete []array; } }
其中,创建动态struct数组
struct struct_name * struct_array = new struct_name[struct_array_len];
输入struct数组元素值,记得不要落下&
scanf("%d",&struct_array[i].struct_member);
排序
sort(struct_array,struct_array+struct_array_len,compare);
释放
delete []struct_array;