PRoblem Description
小鑫是個商人,當然商人最希望的就是多賺錢,小鑫也一樣。 這天,他來到了一個遙遠的國度。那里有著n件商品,對于第i件商品需要付出ci的價錢才能得到。當然,對于第i件商品,小鑫在自己心中有一個估價pi:代表著當他買下這件商品后帶回他的國家可以賣出的價格。小鑫只能帶回m件商品,你能幫他計算一下他最多能賺多少錢么?Input
輸入有多組,到文件結束。(注:數據有很多組,請用高效率算法)對于每一組數據。第一行是n,m。m≤n≤10000000。緊接著有n行,每一行有兩個數 c ,p。第i行代表著ci,pi。ci≤pi數據都在int范圍內 。 Output
對于每組輸入數據只輸出一行一個數,代表小鑫能賺多少錢。 Example Input
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; }