原文链接:河南省第三届ACM-BUYING FEED
题目大意:
在一条路上(直线),一个农夫需要购买need个feed,这条路上不同位置有若干个商店,每个商店中的feed的数量和价格都不一样。并且每运输一个单位feed经过一个单位的距离都要花费1cent。让求最小的花费。
解题思路:
突然诈尸,哈哈哈,失踪人口回归,大家肯定都想我了吧(其实没人看。。。)下面进入正题。
一开因为没仔细没仔细看题目,在运输费用上产生了点疑问就去看了看别人的博客,偶然看到运输费用应该表示为m-n(m:总距离,n:商店所在位置)之后恍然大悟。
只按feed的价格来贪心是不够的,还要把运费加上,而运费就是上面所说的m-n,之后每次都贪心最小的,直到满足需求就可以了。想明白这一点之后题目很简单。
代码:
#pragma warning(disable : 4996)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<map>
#define LOCAL
using namespace std;
const int MAXN = 100 + 10;
struct store {
int x;//位置
int f;//最多多少个
int c;//价格
int pc;//单位个需要的总价格:单价+运费
//bool operator < (const store a) {
// return pc < a.pc;
//}
};
bool cmp(const store a, const store b) {
return a.pc < b.pc;
}
store s[MAXN];
int main()
{
#ifdef LOCAL
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
while (n--) {
int need, E, m, sum = 0;
cin >> need >> E >> m;
for (int i = 0; i < m; i++) {
cin >> s[i].x >> s[i].f >> s[i].c;
s[i].pc = s[i].c + (E - s[i].x);//算出该商店feed的平均总价格
}
sort(s, s+m, cmp);//按照总单价从小到大排序
for (int i = 0; i < m; i++) {
if (need > s[i].f) {//不够就全买下来,应为当前的 pc 是最小的
need -= s[i].f;
sum += s[i].f * s[i].pc;
}
else {//够need个了,加完退出
sum += need * s[i].pc;
break;
}
}
cout << sum << endl;
}
return 0;
}