4 21 21 32 23 4Example Output
3下面是用两种方法做的。第一种是C语言的快排,第二种是用了C++的sort函数。一、#include<stdio.h> struct node{ int c; int p; int har;}size[10000001];int partition(struct node size[],int low,int high){ int key=size[low].har; while(low<high) { while(low<high&&size[high].har<=key) high--; size[low]=size[high]; while(low<high&&size[low].har>=key) low++; size[high]=size[low]; } size[low].har=key; return low;}void qsort(struct node size[],int left,int right){ int x; if(left<right) { x=partition(size,left,right); qsort(size,left,x-1); qsort(size,x+1,right); }}int main(){ int n,m,sum,i; while(~scanf("%d %d",&n,&m)) { sum=0; for(i=0;i<n;i++) { scanf("%d %d",&size[i].c,&size[i].p); size[i].har=size[i].p-size[i].c; } qsort(size,0,n-1); for(i=0;i<m;i++) sum+=size[i].har; printf("%d/n",sum); } return 0;}二、 #include<stdio.h> #include<algorithm> using namespace std; struct node { int c; int p; int b; }size[10000001]; int cmp(node a,node b) { return a.b>b.b; } int main() { int n,m,i,sum; while(~scanf("%d%d",&n,&m)) { sum=0; for(i=0;i<n;i++) { scanf("%d%d",&size[i].c,&size[i].p); size[i].b=size[i].p-size[i].c; } sort(size,size+n,cmp); for(i=0;i<m;i++) { sum=sum+size[i].b; } printf("%d/n",sum); } return 0; }
新闻热点
疑难解答