跳到正文

算法·理论

几种单源最短路的做法

zyxvxyz约 38 分钟
原文
文章信息与版本

文章信息

发布
2024年9月24日
收录
2026年8月8日
更新
2026年11月14日
篇幅
约 38 分钟
获赞
2

版本

  1. v1当前

摘要

问题

最短路问题:输入 n,m 代表 n 个点,m 条边。 接下来 m 行,为起点到终点的一条边。最后一行为起点节点和终点节点。

前提条件

所有输入的节点和边的参数均在有效范围内,具体的不会超时的数值已经放在每份代码前。 本算法的结构和实现参考了已有的相关研究。 下文中的不会超时的定义为:此代码在1秒内(不包含1秒)可给出正确的答案。

附加

下文中代码的提示词可删除。

正文

迪杰斯特拉

最为经典的 迪杰斯特拉 算法,时间复杂度为 O(n2)O(n^2) 在 n<104n<10^4 时不会超时。

注意:算法适用于非负权重图,而 Bellman-Ford 与 SPFA 算法可以处理负权重图。
C++
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
struct Edge {
    int to;
    int weight;
};
vector<int> dijkstra(int n, int start, const vector<vector<Edge>>& graph) {
    vector<int> dist(n + 1, INF);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // 最小堆
    dist[start] = 0;
    pq.push({0, start});
    while (!pq.empty()) {
        int u = pq.top().second;
        pq.pop();
        for (const Edge& edge : graph[u]) {
            int v = edge.to;
            int weight = edge.weight;
            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }
    return dist;
}
int main() {
    int n, m;
    cout << "请输入节点数 n 和边数 m: ";
    cin >> n >> m;
    vector<vector<Edge>> graph(n + 1);
    cout << "请输入每条边的起点、终点和权重:\n";
    for (int i = 0; i < m; ++i) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].push_back({v, w});
        graph[v].push_back({u, w});
    }
    int start, end;
    cout << "起点和终点: ";
    cin >> start >> end;
    vector<int> distances = dijkstra(n, start, graph);
    if (distances[end] == INF) {
        cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
    } else {
        cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << distances[end] << endl;
    }
    return 0;
}

堆优化的迪杰斯特拉

堆优化的迪杰斯特拉 算法,时间复杂度为 O((n+m)log2n)O((n+m)log_2n) 在 n<105n<10^5 时不会超时。

注意:算法适用于非负权重图,而 Bellman-Ford 与 SPFA 算法可以处理负权重图。
C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
void dijkstra(int n, int m, vector<tuple<int, int, int>>& edges, int start, int end) {
    vector<vector<pair<int, int>>> graph(n + 1);
    for (const auto& [u, v, w] : edges) {
        graph[u].emplace_back(v, w);
        graph[v].emplace_back(u, w);
    }
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    vector<int> dist(n + 1, INF);
    dist[start] = 0;
    pq.emplace(0, start);
    while (!pq.empty()) {
        auto [current_dist, current_node] = pq.top();
        pq.pop();
        if (current_dist > dist[current_node]) {
            continue;
        }
        for (const auto& [neighbor, weight] : graph[current_node]) {
            int distance = current_dist + weight;
            if (distance < dist[neighbor]) {
                dist[neighbor] = distance;
                pq.emplace(distance, neighbor);
            }
        }
    }
    if (dist[end] != INF) {
        cout << dist[end] << endl;
    } else {
        cout << -1 << endl;
    }
}
int main() {
    int n, m;
    cin >> n >> m;
    vector<tuple<int, int, int>> edges(m);
    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        edges[i] = make_tuple(u, v, w);
    }
    int start, end;
    cin >> start >> end;
    dijkstra(n, m, edges, start, end);
    return 0;
}

SPFA 算法

SPFA 算法,时间复杂度为 O(nm) O(n2)O(nm)~O(n^2) 在 n<106n<10^6 时不会超时。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
void spfa(int n, int m, vector<vector<pair<int, int>>>& graph, int start, int end) {
	vector<int> dist(n + 1, INF);
	dist[start] = 0;
	queue<int> q;
	q.push(start);
	while (!q.empty()) {
		int current_node = q.front();
		q.pop();
		for (const auto& [neighbor, weight] : graph[current_node]) {
			if (dist[current_node] + weight < dist[neighbor]) {
				dist[neighbor] = dist[current_node] + weight;
				q.push(neighbor);
			}
		}
	}
	if (dist[end] != INF) {
		cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << dist[end] << endl;
	} else {
		cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
	}
}
int main() {
	int n, m;
	cin >> n >> m;
	vector<vector<pair<int, int>>> graph(n + 1);
	for (int i = 0; i < m; i++) {
		int u, v, w;
		cin >> u >> v >> w;
		graph[u].emplace_back(v, w);
		graph[v].emplace_back(u, w);
	}
	int start, end;
	cin >> start >> end;
	spfa(n, m, graph, start, end);
	return 0;
}

防止二次入队的 SPFA

防止二次入队的 SPFA ,时间复杂度为 O(nm) O(n2)O(nm)~O(n^2) 在 n<106n<10^6 时不会超时。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
void spfa(int n, int m, vector<vector<pair<int, int>>>& graph, int start, int end) {
    vector<int> dist(n + 1, INF);
    vector<bool> inQueue(n + 1, false);
    dist[start] = 0;
    queue<int> q;
    q.push(start);
    inQueue[start] = true;
    while (!q.empty()) {
        int current_node = q.front();
        q.pop();
        inQueue[current_node] = false;
        for (const auto& [neighbor, weight] : graph[current_node]) {
            if (dist[current_node] + weight < dist[neighbor]) {
                dist[neighbor] = dist[current_node] + weight;
                if (!inQueue[neighbor]) {
                    q.push(neighbor);
                    inQueue[neighbor] = true;
                }
            }
        }
    }
    if (dist[end] != INF) {
        cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << dist[end] << endl;
    } else {
        cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
    }
}
int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<pair<int, int>>> graph(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].emplace_back(v, w);
        graph[v].emplace_back(u, w);
    }
    int start, end;
    cin >> start >> end;
    spfa(n, m, graph, start, end);
    return 0;
}

随机化的 SPFA 算法

随机化的 SPFA 算法,时间复杂度为 O(nm) O(n2)O(nm)~O(n^2) 在 n<106n<10^6 时不会超时。

具体的分数看当天的人品。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
void random_spfa(int n, int m, vector<vector<pair<int, int>>>& graph, int start, int end) {
    vector<int> dist(n + 1, INF);
    vector<bool> inQueue(n + 1, false);
    dist[start] = 0;
    queue<int> q;
    q.push(start);
    inQueue[start] = true;
    while (!q.empty()) {
        int current_node = q.front();
        q.pop();
        inQueue[current_node] = false;
        vector<pair<int, int>> neighbors = graph[current_node];
        shuffle(neighbors.begin(), neighbors.end(), std::default_random_engine());
        for (const auto& [neighbor, weight] : neighbors) {
            if (dist[current_node] + weight < dist[neighbor]) {
                dist[neighbor] = dist[current_node] + weight;
                if (!inQueue[neighbor]) {
                    q.push(neighbor);
                    inQueue[neighbor] = true;
                }
            }
        }
    }
    if (dist[end] != INF) {
        cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << dist[end] << endl;
    } else {
        cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
    }
}
int main() {
    int n, m;
    cout << "请输入节点数 n 和边数 m: ";
    cin >> n >> m;
    vector<vector<pair<int, int>>> graph(n + 1);
    cout << "请输入每条边的起点、终点和权重:\n";
    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].emplace_back(v, w);
        graph[v].emplace_back(u, w);
    }
    int start, end;
    cout << "起点和终点: ";
    cin >> start >> end;
    random_spfa(n, m, graph, start, end);
    return 0;
}

Bellman-Ford 算法

Bellman-Ford 算法,时间复杂度为 O(nm) O(n2)O(nm)~O(n^2) 在 n<104n<10^4 不会超时。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
struct Edge {
    int u, v, w;
};
void bellman_ford(int n, int m, const vector<Edge>& edges, int start, int end) {
    vector<int> dist(n + 1, INF);
    dist[start] = 0;
    for (int i = 1; i <= n - 1; i++) {
        for (const auto& edge : edges) {
            if (dist[edge.u] != INF && dist[edge.u] + edge.w < dist[edge.v]) {
                dist[edge.v] = dist[edge.u] + edge.w;
            }
        }
    }
    for (const auto& edge : edges) {
        if (dist[edge.u] != INF && dist[edge.u] + edge.w < dist[edge.v]) {
            cout << "图中存在负权环!\n";
            return;
        }
    }
    if (dist[end] != INF) {
        cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << dist[end] << endl;
    } else {
        cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
    }
}
int main() {
    int n, m;
    cout << "请输入节点数 n 和边数 m: ";
    cin >> n >> m;
    vector<Edge> edges(m);
    cout << "请输入每条边的起点、终点和权重:\n";
    for (int i = 0; i < m; i++) {
        cin >> edges[i].u >> edges[i].v >> edges[i].w;
    }
    int start, end;
    cout << "请输入起点和终点: ";
    cin >> start >> end;
    bellman_ford(n, m, edges, start, end);
    return 0;
}

包含提前停止功能的 Bellman-Ford 算法

包含提前停止功能的 Bellman-Ford 算法,时间复杂度 O(nm)O(nm),在 n<105n<10^5 时不会超时。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF = numeric_limits<int>::max();
struct Edge {
    int u, v, w;
};
void optimized_bellman_ford(int n, int m, const vector<Edge>& edges, int start, int end) {
    vector<int> dist(n + 1, INF);
    dist[start] = 0;
    bool updated;
    for (int i = 1; i <= n - 1; i++) {
        updated = false;
        for (const auto& edge : edges) {
            if (dist[edge.u] != INF && dist[edge.u] + edge.w < dist[edge.v]) {
                dist[edge.v] = dist[edge.u] + edge.w;
                updated = true;
            }
        }
        if (!updated) break;
    }
    for (const auto& edge : edges) {
        if (dist[edge.u] != INF && dist[edge.u] + edge.w < dist[edge.v]) {
            cout << "图中存在负权环!\n";
            return;
        }
    }
    if (dist[end] != INF) {
        cout << "从节点 " << start << " 到节点 " << end << " 的最短距离为: " << dist[end] << endl;
    } else {
        cout << "从节点 " << start << " 到节点 " << end << " 的路径不存在。\n";
    }
}
int main() {
    int n, m;
    cout << "请输入节点数 n 和边数 m: ";
    cin >> n >> m;
    vector<Edge> edges(m);
    cout << "请输入每条边的起点、终点和权重:\n";
    for (int i = 0; i < m; i++) {
        cin >> edges[i].u >> edges[i].v >> edges[i].w;
    }
    int start, end;
    cout << "请输入起点和终点: ";
    cin >> start >> end;
    optimized_bellman_ford(n, m, edges, start, end);
    return 0;
}

其他算法

接下来的算法会用些难懂,但如果你理解了,会很有趣。然我们开始吧。

node: 这些代码已有了数据,如有需要,请自行输入。具体能否输出正确结果,需看你当天的人品。

进化算法

进化算法(万物皆可进化)时间复杂度为 O(G∗P∗L)O(G*P*L) 在 G,P,LG,P,L 平均 3 个 0 时不会超时。

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

struct Edge {
	int start, end, weight;
};

class GeneticAlgorithm {
	public:
		GeneticAlgorithm(int n, int m, vector<Edge>& edges, int start, int end)
			: n(n), m(m), start(start), end(end), edges(edges) {
			createGraph();
			populationSize = 100;
			generations = 100;
		}

		void run() {
			initializePopulation();

			for (int i = 0; i < generations; ++i) {
				vector<vector<int>> selected = select();
				vector<vector<int>> newPopulation = selected;

				while (newPopulation.size() < populationSize) {
					vector<int> parent1 = selected[rand() % selected.size()];
					vector<int> parent2 = selected[rand() % selected.size()];
					vector<int> child = crossover(parent1, parent2);
					mutate(child);
					if (isValidPath(child)) {
						newPopulation.push_back(child);
					}
				}

				population = newPopulation;
			}

			auto bestPath = *min_element(population.begin(), population.end(),
			[this](const vector<int>& a, const vector<int>& b) {
				return fitness(a) < fitness(b);
			});

			cout << "最优路径: ";
			for (int node : bestPath) {
				cout << node << " ";
			}
			cout << ",路径总权重: " << fitness(bestPath) << endl;
		}

	private:
		int n, m, start, end, populationSize, generations;
		vector<Edge> edges;
		vector<vector<pair<int, int>>> graph;
		vector<vector<int>> population;

		void createGraph() {
			graph.resize(n);
			for (const auto& edge : edges) {
				graph[edge.start].emplace_back(edge.end, edge.weight);
			}
		}

		void initializePopulation() {
			population.clear();
			for (int i = 0; i < populationSize; ++i) {
				vector<int> path = { start };
				unordered_set<int> visited;
				visited.insert(start);

				while (true) {
					int current = path.back();
					if (current == end) break;

					vector<int> neighbors;
					for (const auto& neighbor : graph[current]) {
						if (visited.find(neighbor.first) == visited.end()) {
							neighbors.push_back(neighbor.first);
						}
					}

					if (neighbors.empty()) break;
					int nextNode = neighbors[rand() % neighbors.size()];
					path.push_back(nextNode);
					visited.insert(nextNode);
				}
				if (path.back() != end) {
					path.push_back(end);
				}
				if (isValidPath(path)) {
					population.push_back(path);
				}
			}
		}

		bool isValidPath(const vector<int>& path) {
			for (size_t i = 0; i < path.size() - 1; ++i) {
				bool valid = false;
				for (const auto& neighbor : graph[path[i]]) {
					if (neighbor.first == path[i + 1]) {
						valid = true;
						break;
					}
				}
				if (!valid) return false;
			}
			return true;
		}

		int fitness(const vector<int>& path) {
			int totalWeight = 0;
			for (size_t i = 0; i < path.size() - 1; ++i) {
				int current = path[i];
				for (const auto& neighbor : graph[current]) {
					if (neighbor.first == path[i + 1]) {
						totalWeight += neighbor.second;
						break;
					}
				}
			}
			return totalWeight;
		}

		vector<vector<int>> select() {
			sort(population.begin(), population.end(),
			[this](const vector<int>& a, const vector<int>& b) {
				return fitness(a) < fitness(b);
			});
			vector<vector<int>> selected(population.begin(), population.begin() + population.size() / 2);
			return selected;
		}

		vector<int> crossover(const vector<int>& parent1, const vector<int>& parent2) {
			vector<int> child = parent1;
			int size = min(parent1.size(), parent2.size());
			int point = rand() % (size - 1) + 1;

			for (int i = point; i < parent2.size(); ++i) {
				if (find(child.begin(), child.end(), parent2[i]) == child.end()) {
					child.push_back(parent2[i]);
				}
			}
			return child;
		}

		void mutate(vector<int>& path) {
			if (path.size() > 2) {
				int i = rand() % (path.size() - 2) + 1;
				int j = rand() % (path.size() - 2) + 1;
				swap(path[i], path[j]);
			}
		}
};

int main() {
	int n = 5; // 点数
	int m = 7; // 边数
	vector<Edge> edges = {  //图
		{0, 1, 1},
		{1, 2, 1},
		{0, 3, 5},
		{3, 4, 1},
		{4, 2, 2},
		{1, 4, 3},
		{2, 4, 5}
	};

	int start = 0; // 起点
	int end = 2; // 终点

	GeneticAlgorithm ga(n, m, edges, start, end);
	ga.run();

	return 0;
}

退火模拟

退火模拟 时间复杂度为 O(k∗t∗n)O(k*t*n) 在 k,t,nk,t,n 平均 3 个 0 时不会超时。

C++
#include<bits/stdc++.h>
using namespace std;
struct Edge {
    int start, end, weight;
};
class SimulatedAnnealing {
public:
    SimulatedAnnealing(int n, const vector<Edge>& edges, int start, int end)
        : n(n), edges(edges), start(start), end(end) {
        createGraph();
    }
    void run(int iterations) {
        double globalBestCost = numeric_limits<double>::infinity();
        vector<int> globalBestPath;
        for (int i = 0; i < iterations; ++i) {
            double bestCost;
            vector<int> bestPath = anneal(bestCost);
            if (bestCost < globalBestCost) {
                globalBestCost = bestCost;
                globalBestPath = bestPath;
            }
        }
        cout << "全局最优路径: ";
        for (int node : globalBestPath) {
            cout << node << " ";
        }
        cout << ",路径总权重: " << globalBestCost << endl;
    }
private:
    int n;
    vector<Edge> edges;
    vector<vector<pair<int, int> > > graph;
    int start, end;
    double initialTemp = 10000;
    double minTemp = 1.0;
    double coolingRate = 0.995;
    void createGraph() {
        graph.resize(n);
        for (const auto& edge : edges) {
            graph[edge.start].emplace_back(edge.end, edge.weight);
        }
    }
    vector<int> generateInitialSolution() {
        vector<int> path = { start };
        vector<bool> visited(n, false);
        visited[start] = true;
        while (true) {
            int current = path.back();
            if (current == end) break;
            vector<int> neighbors;
            for (const auto& neighbor : graph[current]) {
                if (!visited[neighbor.first]) {
                    neighbors.push_back(neighbor.first);
                }
            }
            if (neighbors.empty()) break;
            int nextNode = neighbors[rand() % neighbors.size()];
            path.push_back(nextNode);
            visited[nextNode] = true;
        }
        
        if (path.back() != end) {
            path.push_back(end);
        }
        return path;
    }
    vector<int> generateNeighbor(const vector<int>& current) {
        vector<int> neighbor = current;
        if (neighbor.size() > 2) {
            int i = rand() % (neighbor.size() - 2) + 1;
            int j = rand() % (neighbor.size() - 2) + 1;
            swap(neighbor[i], neighbor[j]);
        }
        return neighbor;
    }
    double fitness(const vector<int>& path) {
        double totalWeight = 0;
        for (size_t i = 0; i < path.size() - 1; ++i) {
            int current = path[i];
            bool found = false;
            for (const auto& neighbor : graph[current]) {
                if (neighbor.first == path[i + 1]) {
                    totalWeight += neighbor.second;
                    found = true;
                    break;
                }
            }
            if (!found) return numeric_limits<double>::infinity();
        }
        return totalWeight;
    }
    double acceptanceProbability(double bestCost, double newCost, double temp) {
        if (newCost < bestCost) {
            return 1.0;
        }
        return exp((bestCost - newCost) / temp);
    }
    vector<int> anneal(double& bestCost) {
        double currentTemp = initialTemp;
        vector<int> bestPath = generateInitialSolution();
        bestCost = fitness(bestPath);
        while (currentTemp > minTemp) {
            vector<int> newPath = generateNeighbor(bestPath);
            double newCost = fitness(newPath);
            if (acceptanceProbability(bestCost, newCost, currentTemp) > ((double) rand() / RAND_MAX)) {
                bestPath = newPath;
                bestCost = newCost;
            }

            currentTemp *= coolingRate;
        }
        return bestPath;
    }
};
int main() {
    int n = 5; // 点数
    vector<Edge> edges = {
        {0, 1, 1},
        {1, 2, 1},
        {0, 3, 5},
        {3, 4, 1},
        {4, 2, 2},
        {1, 4, 3},
        {2, 4, 5}
    };
    int start = 0; // 起点
    int end = 2; // 终点
    SimulatedAnnealing sa(n, edges, start, end);
    int iterations = 500; // 设置多次退火的次数
    sa.run(iterations);
    return 0;
}

尾声

当你做任何算法题时,如果能像本文一样,像做 A+B 问题时,用任何算法都能游刃有余的解决,你在算法方面一定能有所成就。 You can do better than this. The story has not yet begun, not the time to end.

THE END

原文