Think:
1感觉自己的代码可能会超时,但是提交AC,自己需要思考更优化的算法
2贪心算法思想:由当前的最优解最终得到最终最优解(局部最优解得到最终最优解)
商人小鑫
Time Limit: 1000MS Memory Limit: 65536KB
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
Hint
Author
lin
以下为Accepted代码——sort()函数
#include <bits/stdc++.h>
using namespace std;
int a[10000004];
int main()
{
int n, m, i, c, p, sum;
while(scanf("%d %d", &n, &m) != EOF)
{
sum = 0;
for(i = 0; i < n; i++)
{
scanf("%d %d", &c, &p);
a[i] = p-c;
}
sort(a, a+n);
for(i = n-1; i >= n-m; i--)
sum += a[i];
printf("%d\n", sum);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 24ms
Take Memory: 560KB
Submit time: 2017-04-15 15:55:14
****************************************************/
以下为Accepted代码——sort()函数
#include <bits/stdc++.h>
using namespace std;
int a[10000004];
int main()
{
int n, m, i, c, p, sum;
while(scanf("%d %d", &n, &m) != EOF)
{
sum = 0;
for(i = 0; i < n; i++)
{
scanf("%d %d", &c, &p);
a[i] = p-c;
}
sort(a, a+n, greater<int>());
for(i = 0; i < m; i++)
sum += a[i];
printf("%d\n", sum);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 40ms
Take Memory: 556KB
Submit time: 2017-04-15 15:59:37
****************************************************/
以下为Accepted代码——qsort()函数
#include <bits/stdc++.h>
using namespace std;
int a[10000004];
int cmp(const void *a, const void *b)
{
return ((*(int *)a) - (*(int *)b));
}
int main()
{
int n, m, i, c, p, sum;
while(scanf("%d %d", &n, &m) != EOF)
{
sum = 0;
for(i = 0; i < n; i++)
{
scanf("%d %d", &c, &p);
a[i] = p-c;
}
qsort(&a[0], n, sizeof(a[0]), cmp);
for(i = n-1; i >= n-m; i--)
sum += a[i];
printf("%d\n", sum);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 52ms
Take Memory: 960KB
Submit time: 2017-04-15 15:57:49
****************************************************/
以下为Accepted代码——priority_queue()容器
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, i, c, p, sum;
while(scanf("%d %d", &n, &m) != EOF)
{
sum = 0;
priority_queue<int, vector<int>, greater<int> > q;
for(i = 0; i < n; i++)
{
scanf("%d %d", &c, &p);
if((int)q.size() < m)
q.push(p-c);
else
{
q.push(p-c);
q.pop();
}
}
while(!q.empty())
{
sum += q.top();
q.pop();
}
printf("%d\n", sum);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 44ms
Take Memory: 164KB
Submit time: 2017-04-15 16:11:04
****************************************************/

探讨了如何通过选择最优的商品组合使商人小鑫获得最大利润的问题,利用贪心算法思想,通过排序或优先队列选取最高利润的商品。
1892

被折叠的 条评论
为什么被折叠?



