问题描述:
有一批集装箱要装上一艘载重量为 c 的轮船。其中集装箱 i 的重量为 wi 。最优装载问题要求在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。
解析:
该问题形式化描述为:
max∑xi, 1 <= i <= n
∑wixi <= c, 1 <= i <= n
xi ∈{0, 1}, 1 <= i <= n
其符合贪心的两个基本要素:1:贪心选择性质(即所求问题的整体最优解可以通过一系列局部最优的选择--贪心选择达到)
2:最优子结构性质。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1024;
typedef struct Goods
{
int weight;
int id;
};
int x[MAX];
Goods g[MAX];
int c, n, loaded_n;
void Input()
{
scanf("%d %d", &c, &n);
for(int i = 1; i <= n; ++i)
{
scanf("%d", &g[i].weight);
g[i].id = i;
}
}
bool compare(const Goods &a, const Goods &b)
{
return !a.weight < b.weight;
}
void Loading()
{
loaded_n = 0;
memset(x, 0, sizeof(x));
sort(g + 1, g + n, compare);
for(int i = 1; i <= n && c >= g[i].weight; ++i)
{
x[g[i].id] = 1;
c -= g[i].weight;
++loaded_n;
}
}
void Output()
{
cout << "装入了 " << loaded_n << " 件物品" << endl;
cout << "分别是" << endl;
for(int i = 1; i <= n; ++i)
if(x[i] == 1)
cout << i << " ";
}
int main()
{
Input();
Loading();
Output();
}