标签:并且 dev max oat blog names std strong 算法
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int maxn = 10000 + 200;
struct Lorry {
float weight;
float value;
float pro;
Lorry(float w = 0, float v = 0, float pro = 0) :
weight(w), value(v), pro(pro) {}
} lorry[maxn];
//按价值率降序排序
bool cmp(const Lorry& a, const Lorry& b)
{
return a.pro > b.pro;
}
void solve();
void solve()
{
int n;
float w; //物品数量, 核载重量
float ans = 0;
scanf("%d", &n);
cin >> w;
for (int i = 0; i < n; i++) {
cin >> lorry[i].weight >> lorry[i].value;
lorry[i].pro = lorry[i].value / lorry[i].weight;
}
//价值高的在前
sort(lorry, lorry + n, cmp);
for (int i = 0; i < n; i++)
{
if (w == 0) break;
//w > l[i].weight 放心减就好了
if (w - lorry[i].weight > 0) {
w -= lorry[i].weight;
ans += lorry[i].value;
} else {
//否则..全部用来给w, 还有剩余,单价最高嘛
ans += lorry[i].pro * w;
lorry[i].weight -= w;
w = 0;
}
}
printf("%.1f\n", ans);
}
int main()
{
solve();
return 0;
}
//好多简单题贪心算法,都需要定义结构体来组合数据, 并且提供比较函数,方便sort函数排序, 像这样~
struct Lorry {
float weight;
float value;
float pro; //单价
Lorry(float w = 0, float v = 0, float pro = 0) :
weight(w), value(v), pro(pro) {}
} lorry[maxn];
//按价值率降序排序
bool cmp(const Lorry& a, const Lorry& b)
{
return a.pro > b.pro;
}
//来用这个模板写一题,Codevs上的快乐牛奶
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
const int maxM = 5000 + 20; //农民数量
struct Milk {
int amount;
int value;
Milk(int m = 0, int v = 0) : amount(m), value(v) {}
} Farmer[maxM];
void solve();
//按照价格 升序排序
bool cmp(const Milk& a, const Milk& b) {
return a.value < b.value;
}
void solve()
{
int N, M; // N -- 需求, M -- 农民数目
int ans = 0;
scanf("%d%d", &N, &M);
//硬币问题
//最少价格, 刚刚好 N 数量
//应该每次 挑选 单价最低的
for (int i = 0; i < M; i++) {
//输入价格 and 数量
scanf("%d%d", &Farmer[i].value, &Farmer[i].amount);
}
//按照价格 升序排序
sort(Farmer, Farmer + M, cmp);
for (int i = 0; i < M; i++)
{//每次选价格低的先 大于0再执行下面,如果刚刚好为0,则不好直接退出
if (N - Farmer[i].amount > 0) {
N -= Farmer[i].amount;
ans += Farmer[i].amount*Farmer[i].value;
} else {
for (int j = 1; j <= Farmer[i].amount; j++) {
if (N - j == 0) {
N = 0;
ans += Farmer[i].value * j;
printf("%d\n", ans);
return;
}
}
}
}
printf("%d\n", ans);
}
int main()
{
solve();
return 0;
}
标签:并且 dev max oat blog names std strong 算法
原文地址:http://www.cnblogs.com/douzujun/p/6637730.html