Think:
首先, 注意 题目 的要求是求利润, 其次 注意 数据较大 所以要用高效率的算法!!! 这点很重要!!!! 反正我用了sort函数水了, 因为按照利润排序所以 写了一个cmp 来进行交换。
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 2
1 2
1 3
2 2
3 4
Example Output
3
#include<bits/stdc++.h>
using namespace std;
struct node
{
int buy;
int sell;
int w;
}A[10000050];
bool cmp(struct node a, struct node b)
{
return a.w > b.w;
}
int main()
{
int m, n, t;
int earn;
while(scanf("%d %d",&n, &m)!=EOF)
{
earn = 0;
for (t = 0;t <= n - 1;t ++)
{
scanf("%d %d",&A[t].buy,&A[t].sell);
A[t].w = A[t].sell - A[t].buy;
}
sort(A, A + n, cmp);
for (t = 0;t <= m - 1;t ++)
{
earn = earn + A[t].w;
}
printf("%d\n",earn);
}
return 0;
}