SDUT_商人小鑫_貪心

商人小鑫

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

小鑫是個商人,當然商人最希望的就是多賺錢,小鑫也一樣。
這天,他來到了一個遙遠的國度。那裏有着n件商品,對於第i件商品需要付出ci的價錢才能得到。當然,對於第i件商品,小鑫在自己心中有一個估價pi:代表着當他買下這件商品後帶回他的國家可以賣出的價格。小鑫只能帶回m件商品,你能幫他計算一下他最多能賺多少錢麼?

Input

輸入有多組,到文件結束。(注:數據有很多組,請用高效率算法)
對於每一組數據。第一行是n,m。m≤n≤10000000。
緊接着有n行,每一行有兩個數 c ,p。第i行代表着ci,pi。ci≤pi
數據都在int範圍內 。  

Output

對於每組輸入數據只輸出一行一個數,代表小鑫能賺多少錢。

Sample Input

4 2
1 2
1 3
2 2
3 4

Sample Output

3

Hint

#include<stdio.h>
#include<stdlib.h>
#define Max 10000000
typedef struct node{
	int ci;
	int pi; 
	int money;
}thing; 
thing th[Max+10];
int Compare(const void* a,const void* b){  //qsort()比較函數   倒序 
	thing* x=(thing*)a;
	thing* y=(thing*)b;
	return y->money - x->money;          //小於0,a在前 
}
int main(){
	int n,m,sum;
	while(~scanf("%d %d",&n,&m)){
		sum=0;
		for(int i=0;i<n;i++){
			scanf("%d %d",&th[i].ci,&th[i].pi);
			th[i].money=th[i].pi-th[i].ci;
		}
		qsort(th,n,sizeof(thing),Compare);      //使用這個函數排序   
		for(int i=0;i<m;i++){
			sum+=th[i].money; 
		}
		printf("%d\n",sum);
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章