vault backup: 2026-06-10 11:19:43
This commit is contained in:
+56
-23
@@ -58,18 +58,35 @@ flowchart TD
|
||||
|
||||
**贪心策略**:**按结束时间从早到晚排序**,优先选择结束时间早的活动。
|
||||
|
||||
```plaintext
|
||||
function activitySelection(activities):
|
||||
sort activities by finish time
|
||||
selected = [activities[1]] // 选择第一个结束最早的
|
||||
lastFinish = activities[1].finish
|
||||
```cpp
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
using namespace std;
|
||||
|
||||
for i = 2 to n:
|
||||
if activities[i].start >= lastFinish:
|
||||
selected.append(activities[i])
|
||||
lastFinish = activities[i].finish
|
||||
struct Activity {
|
||||
int start, finish;
|
||||
};
|
||||
|
||||
return selected
|
||||
// 活动选择问题:按结束时间贪心选择最多的互不冲突活动
|
||||
vector<int> activitySelection(vector<Activity>& activities) {
|
||||
// 按结束时间从早到晚排序
|
||||
sort(activities.begin(), activities.end(),
|
||||
[](const Activity& a, const Activity& b) {
|
||||
return a.finish < b.finish;
|
||||
});
|
||||
|
||||
vector<int> selected;
|
||||
selected.push_back(0); // 选择第一个结束最早的
|
||||
int lastFinish = activities[0].finish;
|
||||
|
||||
for (int i = 1; i < (int)activities.size(); i++) {
|
||||
if (activities[i].start >= lastFinish) {
|
||||
selected.push_back(i); // 记录被选中的活动下标
|
||||
lastFinish = activities[i].finish;
|
||||
}
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
```
|
||||
|
||||
**解释**:选择结束时间最早的活动,可以为后续活动留出最多的时间空间。每选择一个活动,就排除与其冲突的活动,然后继续在剩余活动中选结束最早的。
|
||||
@@ -83,21 +100,37 @@ function activitySelection(activities):
|
||||
|
||||
**贪心策略**:按**价值密度**(vᵢ/wᵢ)从高到低排序,优先取价值密度最高的物品。
|
||||
|
||||
```plaintext
|
||||
function fractionalKnapsack(items, W):
|
||||
sort items by value/weight ratio descending
|
||||
totalValue = 0
|
||||
remaining = W
|
||||
```cpp
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
using namespace std;
|
||||
|
||||
for each item in items:
|
||||
if item.weight <= remaining:
|
||||
totalValue += item.value
|
||||
remaining -= item.weight
|
||||
else:
|
||||
totalValue += item.value * (remaining / item.weight)
|
||||
break
|
||||
struct Item {
|
||||
double weight, value;
|
||||
};
|
||||
|
||||
return totalValue
|
||||
// 分数背包问题:按价值密度贪心,可取物品的一部分
|
||||
double fractionalKnapsack(vector<Item>& items, double W) {
|
||||
// 按价值密度(value/weight)从高到低排序
|
||||
sort(items.begin(), items.end(),
|
||||
[](const Item& a, const Item& b) {
|
||||
return (a.value / a.weight) > (b.value / b.weight);
|
||||
});
|
||||
|
||||
double totalValue = 0;
|
||||
double remaining = W;
|
||||
|
||||
for (const auto& item : items) {
|
||||
if (item.weight <= remaining) {
|
||||
totalValue += item.value; // 整个物品装入
|
||||
remaining -= item.weight;
|
||||
} else {
|
||||
totalValue += item.value * (remaining / item.weight); // 装入一部分
|
||||
break;
|
||||
}
|
||||
}
|
||||
return totalValue;
|
||||
}
|
||||
```
|
||||
|
||||
**解释**:因为可以取物品的一部分,所以优先取"性价比"最高的物品一定能得到最优解。剩余容量不够装整个物品时,取一部分即可。
|
||||
|
||||
Reference in New Issue
Block a user