几种01背包的做法

· · 算法·理论

摘要

问题描述

01背包:输入 n, m ,代表 n 个元素,m 的质量,下面 n 行,为 v_i 和 m_i 代表 i 号物品的价值和体积。 输出最大价值。

闲话

今天人品不错,适合做算法。先来01背包吧。

前提条件

这些数都在可取范围内。 如有雷同,纯属巧合。

正文

传统的01背包 dp : O(nm) 平均4个0。

#include <bits/stdc++.h>
using namespace std;

vector<int> v(1000 + 1);
vector<int> w(1000 + 1);
vector<vector<int>> f(1000 + 1, vector<int>(10000 + 1, 0));

int main() {
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        cin >> v[i] >> w[i];
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= m; ++j) {
            f[i][j] = f[i - 1][j];
            if (j >= w[i]) {
                f[i][j] = max(f[i][j], f[i - 1][j - w[i]] + v[i]);
            }
        }
    }
    cout << f[n][m] << endl;
    return 0;
}

压缩状态的 dp :

```cpp #include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> v(n + 1); vector<int> w(n + 1); vector<int> f(m + 1, 0); for (int i = 1; i <= n; ++i) { cin >> v[i] >> w[i]; } for (int i = 1; i <= n; ++i) { for (int j = m; j >= w[i]; --j) { f[j] = max(f[j], f[j - w[i]] + v[i]); } } cout << f[m] << endl; return 0; } ``` 不加优化的 dfs : $O(2^n)$ 中 $n<20$ 时不会超时。 ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v, w; int maxValue = 0; void dfs(int index, int currentWeight, int currentValue) { if (currentWeight <= m) { maxValue = max(maxValue, currentValue); } for (int i = index; i < n; i++) { dfs(i + 1, currentWeight + w[i], currentValue + v[i]); } } int main() { cin >> n >> m; v.resize(n); w.resize(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } dfs(0, 0, 0); cout << maxValue << endl; return 0; } ``` 加了记忆化的 dfs : $O(n*m)$ 平均4个0,因其速度和掌握难度较低,所以在考场上建议使用。~~受限于难度,几乎没有人会在考场上用 dp 做这道题(一些人除外)~~ ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v; vector<int> w; vector<vector<int>> memo; int dfs(int index, int currentWeight) { if (currentWeight > m || index >= n) { return 0; } if (memo[index][currentWeight] != -1) { return memo[index][currentWeight]; } int includeItem = dfs(index + 1, currentWeight + w[index]) + v[index]; int excludeItem = dfs(index + 1, currentWeight); memo[index][currentWeight] = max(includeItem, excludeItem); return memo[index][currentWeight]; } int main() { cin >> n >> m; v.resize(n); w.resize(n); memo.resize(n + 1, vector<int>(m + 1, -1)); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } int maxValue = dfs(0, 0); cout << maxValue << endl; return 0; } ``` 广搜 bfs : $O(2^n)$ $n<20$时不会超时,其速度较慢。 ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v, w; int maxValue = 0; void bfs(int index, int currentWeight, int currentValue) { queue<pair<int, int>> q; q.push(make_pair(index, currentWeight)); while (!q.empty()) { int i = q.front().first; int j = q.front().second; q.pop(); if (j <= m) { maxValue = max(maxValue, currentValue); } for (int k = i; k < n; k++) { if (j + w[k] <= m) { q.push(make_pair(k, j + w[k])); } } } } int main() { cin >> n >> m; v.resize(n); w.resize(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } bfs(0, 0, 0); cout << maxValue << endl; return 0; } ``` 加了记忆化的 bfs : $O(n*m)$ 平均4个0,速度快,受限于STL常数项较大,相比于dfs稍慢,但仍然可以接受,建议使用(略微难于理解,但是比 dp 好理解)。 ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v; vector<int> w; vector<vector<int>> memo; int bfs(int index, int currentWeight) { if (currentWeight > m || index >= n) { return 0; } if (memo[index][currentWeight] != -1) { return memo[index][currentWeight]; } int includeItem = bfs(index + 1, currentWeight + w[index]) + v[index]; int excludeItem = bfs(index + 1, currentWeight); memo[index][currentWeight] = max(includeItem, excludeItem); return memo[index][currentWeight]; } int main() { cin >> n >> m; v.resize(n); w.resize(n); memo.resize(n + 1, vector<int>(m + 1, -1)); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } int maxValue = bfs(0, 0); cout << maxValue << endl; return 0; } ``` 用了优先队列的 bfs (实现方式的不同,会改变它的名字(它的另一个是进化算法)(魏陈的算法)): 速度快,其速度取决于判断是否存在更优解的效率,但一般情况下比 bfs 快 ~~(是且仅是在某些情况下)~~。 ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v, w; int maxValue = 0; int bfs(int index, int currentWeight, int currentValue) { priority_queue<pair<int, int> > q; q.push(make_pair(-currentValue, currentWeight)); while (!q.empty()) { int i = -q.top().first; int j = q.top().second; q.pop(); if (j <= m) { maxValue = max(maxValue, currentValue); } for (int k = i; k < n; k++) { if (j + w[k] <= m) { q.push(make_pair(-(currentValue + v[k]), j + w[k])); } } } return maxValue; } int main() { cin >> n >> m; v.resize(n); w.resize(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } bfs(0, 0, 0); cout << maxValue << endl; return 0; } ``` 同时使用标记数组和优先队列的 bfs : 速度快,其速度取决于判断是否存在更优解的效率,但一般情况下比 bfs 快 ~~(是且仅是在某些情况下)~~。 ```cpp #include<bits/stdc++.h> using namespace std; int n, m; vector<int> v, w; int maxValue = 0; int bfs(int index, int currentWeight, int currentValue) { priority_queue<pair<int, int> > q; q.push(make_pair(-currentValue, currentWeight)); vector<vector<bool>> mark(n, vector<bool>(m + 1, false)); while (!q.empty()) { int i = -q.top().first; int j = q.top().second; q.pop(); if (j <= m) { maxValue = max(maxValue, currentValue); } if (mark[i][j]) { continue; } mark[i][j] = true; for (int k = i; k < n; k++) { if (j + w[k] <= m) { q.push(make_pair(-(currentValue + v[k]), j + w[k])); } } } return maxValue; } int main() { cin >> n >> m; v.resize(n); w.resize(n); for (int i = 0; i < n; i++) { cin >> v[i] >> w[i]; } bfs(0, 0, 0); cout << maxValue << endl; return 0; } ``` # 进阶 ### 接下来的算法会用些难懂,但如果你理解了,会很有趣。然我们开始吧。 #### node: 这些代码已有了数据,如有需要,请自行输入。具体能否输出正确结果,需看你当天的人品。 遗传算法: $O(G*P*n)$ 中 $G$ 为进化的代数,$P$ 为种群大小,$n$ 为基因长度,一般情况下比上述算法慢,~~但仍然可以接受~~,常用于~~炫耀~~积攒功德,试验运气等。 ```cpp #include<bits/stdc++.h> using namespace std; struct Individual { vector<int> genes; int fitness; }; int calculateFitness(const Individual& individual, const vector<int>& values, const vector<int>& weights, int capacity) { int totalValue = 0; int totalWeight = 0; for (size_t i = 0; i < individual.genes.size(); ++i) { if (individual.genes[i] == 1) { totalValue += values[i]; totalWeight += weights[i]; } } return (totalWeight > capacity) ? 0 : totalValue; } Individual selection(const vector<Individual>& population, const vector<int>& values, const vector<int>& weights, int capacity) { int totalFitness = 0; for (const auto& ind : population) { totalFitness += ind.fitness; } int randomValue = rand() % totalFitness; int cumulativeFitness = 0; for (const auto& ind : population) { cumulativeFitness += ind.fitness; if (cumulativeFitness >= randomValue) { return ind; } } return population[0]; } void crossover(Individual& child1, Individual& child2) { int point = rand() % child1.genes.size(); for (int i = point; i < child1.genes.size(); ++i) { swap(child1.genes[i], child2.genes[i]); } } void mutate(Individual& individual, double mutationRate) { for (size_t i = 0; i < individual.genes.size(); ++i) { if ((double)rand() / RAND_MAX < mutationRate) { individual.genes[i] = 1 - individual.genes[i]; } } } Individual geneticAlgorithm(const vector<int>& values, const vector<int>& weights, int capacity, int populationSize, int generations, double mutationRate) { vector<Individual> population(populationSize); for (auto& ind : population) { ind.genes.resize(values.size()); for (size_t i = 0; i < ind.genes.size(); ++i) { ind.genes[i] = rand() % 2; } ind.fitness = calculateFitness(ind, values, weights, capacity); } for (int gen = 0; gen < generations; ++gen) { vector<Individual> newPopulation; for (int i = 0; i < populationSize; i += 2) { Individual parent1 = selection(population, values, weights, capacity); Individual parent2 = selection(population, values, weights, capacity); Individual child1 = parent1, child2 = parent2; crossover(child1, child2); mutate(child1, mutationRate); mutate(child2, mutationRate); child1.fitness = calculateFitness(child1, values, weights, capacity); child2.fitness = calculateFitness(child2, values, weights, capacity); newPopulation.push_back(child1); newPopulation.push_back(child2); } population = move(newPopulation); } Individual bestIndividual = *max_element(population.begin(), population.end(), [](const Individual& a, const Individual& b) { return a.fitness < b.fitness; }); return bestIndividual; } int main() { srand(static_cast<unsigned int>(time(0))); int n = 3; int m = 10; vector<int> values = {1,2,3}; vector<int> weights = {11,7,3}; Individual bestSolution = geneticAlgorithm(values, weights, m, 50, 100, 0.01); cout << "Optimal(0/1):"; for (int gene : bestSolution.genes) { cout << gene << " "; } cout << endl; cout << "max values:" << bestSolution.fitness << endl; return 0; } ``` 退火模拟: $O(G*n)$ 中 $G$ 为退火的次数,$n$ 为物品个数。平均4个0,可以接受。 这个算法适合多次求解,取最大值。 ```cpp #include<bits/stdc++.h> using namespace std; pair<int, int> evaluateSolution(const vector<int>& weights, const vector<int>& values, const vector<int>& solution) { int totalValue = 0; int totalWeight = 0; for (size_t i = 0; i < solution.size(); ++i) { if (solution[i] == 1) { totalValue += values[i]; totalWeight += weights[i]; } } return {totalValue, totalWeight}; } vector<int> generateNeighbor(const vector<int>& solution) { vector<int> neighbor = solution; int idx = rand() % neighbor.size(); neighbor[idx] = 1 - neighbor[idx]; return neighbor; } bool acceptNewSolution(int oldValue, int newValue, double temperature) { if (newValue > oldValue) { return true; } double acceptanceProb = exp((newValue - oldValue) / temperature); return (rand() / (RAND_MAX + 1.0)) < acceptanceProb; } vector<int> simulatedAnnealing(const vector<int>& weights, const vector<int>& values, int capacity, double initialTemperature, double coolingRate) { size_t n = values.size(); vector<int> currentSolution(n, 0); vector<int> bestSolution = currentSolution; auto [bestValue, bestWeight] = evaluateSolution(weights, values, bestSolution); double temperature = initialTemperature; while (temperature > 1) { vector<int> neighbor = generateNeighbor(currentSolution); auto [newValue, newWeight] = evaluateSolution(weights, values, neighbor); if (newWeight <= capacity && acceptNewSolution(bestValue, newValue, temperature)) { currentSolution = neighbor; if (newValue > bestValue) { bestSolution = neighbor; bestValue = newValue; } } temperature *= coolingRate; } return bestSolution; } int main() { srand(static_cast<unsigned int>(time(0))); int n = 3; int m = 10; vector<int> values = {1, 2, 3}; vector<int> weights = {11, 7, 3}; double initialTemperature = 1000; double coolingRate = 0.95; vector<int> bestSolution = simulatedAnnealing(weights, values, m, initialTemperature, coolingRate); cout << "Optimal(0/1): "; for (int gene : bestSolution) { cout << gene << " "; } auto [maxValue, totalWeight] = evaluateSolution(weights, values, bestSolution); cout << endl; cout << "max values: " << maxValue << " & weight: " << totalWeight << endl; return 0; } ``` # 尾声 当你做任何算法题时,如果能像本文一样,像做 A+B 问题时,用任何算法都能游刃有余的解决,那你AK万物就有希望了。 You can do better than this. The story has not yet begun, not the time to end. THE END