import random import heapq # 生成无向图 def generate_graph(n, p): graph = [[0] * n for _ in range(n)] for i in range(n): for j in range(i+1, n): if random.random() < p: graph[i][j] = graph[j][i] = random.randint(1, 10) return graph # Prim算法求最小生成树 def prim(graph): n = len(graph) visited = [False] * n heap = [(0, 0)] mst = [] while heap: weight, node = heapq.heappop(heap) if visited[node]: continue visited[node] = True mst.append((weight, node)) for i in range(n): if not visited[i] and graph[node][i] > 0: heapq.heappush(heap, (graph[node][i], i)) return mst # Kruskal算法求最小生成树 def kruskal(graph): n = len(graph) edges = [] for i in range(n): for j in range(i+1, n): if graph[i][j] > 0: edges.append((graph[i][j], i, j)) edges.sort() parent = list(range(n)) mst = [] for weight, u, v in edges: pu, pv = find(parent, u), find(parent, v) if pu != pv: mst.append((weight, u, v)) parent[pu] = pv return mst def find(parent, x): if parent[x] != x: parent[x] = find(parent, parent[x]) return parent[x] # 生成图 graph = generate_graph(10, 0.6) print(graph) mst_prim = prim(graph) print("Prim算法求最小生成树:", mst_prim) mst_kruskal = kruskal(graph) print("Kruskal算法求最小生成树:", mst_kruskal) # Dijkstra算法求最短路径 def dijkstra(graph, start, end): n = len(graph) dist = [float('inf')] * n dist[start] = 0 visited = [False] * n heap = [(0, start)] while heap: d, u = heapq.heappop(heap) if visited[u]: continue visited[u] = True for v in range(n): if graph[u][v] > 0: if dist[u] + graph[u][v] < dist[v]: dist[v] = dist[u] + graph[u][v] heapq.heappush(heap, (dist[v], v)) return dist[end] # Bellman-Ford算法求最短路代码分析
时间: 2024-03-30 16:38:55 浏览: 62
这段代码主要实现了生成无向图、Prim算法和Kruskal算法求最小生成树、Dijkstra算法和Bellman-Ford算法求最短路径。具体分析如下:
1. 生成无向图:通过调用generate_graph函数,可以生成一个无向图,其中n表示节点数,p表示两个节点之间有边的概率,边的权重是随机生成的。
2. Prim算法求最小生成树:通过调用prim函数,可以求出一个无向图的最小生成树,返回的是由边和对应权重组成的列表。prim函数通过维护一个堆heap来实现,每次取出堆顶元素,并将与该节点相邻的未访问节点加入堆中。
3. Kruskal算法求最小生成树:通过调用kruskal函数,同样可以求出一个无向图的最小生成树,返回的也是由边和对应权重组成的列表。kruskal函数通过将图中所有边按权重从小到大排序,然后依次加入到生成树中去,同时使用并查集来判断是否形成环。
4. Dijkstra算法求最短路径:通过调用dijkstra函数,可以求出一个无向图中从起点到终点的最短路径长度。dijkstra函数同样维护一个堆heap,每次取出堆顶元素,并将与该节点相邻的节点加入堆中,同时更新起点到这些节点的距离。
5. Bellman-Ford算法求最短路:通过调用bellman_ford函数,同样可以求出一个无向图中从起点到终点的最短路径长度。bellman_ford函数通过不断进行松弛操作来更新起点到各个节点的距离,同时也可以检测负权环的存在。
相关问题
import heapqdef prim(graph, start): n = len(graph) visited = [False] * n distance = [float('inf')] * n distance[start] = 0 heap = [(0, start)] while heap: _, u = heapq.heappop(heap) if visited[u]: continue visited[u] = True for v, w in graph[u]: if not visited[v] and w < distance[v]: distance[v] = w heapq.heappush(heap, (w, v)) return sum(distance)def min_distance_sum(graph): n = len(graph) min_distance = float('inf') for i in range(n): distance_sum = prim(graph, i) min_distance = min(min_distance, distance_sum) return min_distancegraph = [ [(1, 2), (2, 1)], [(0, 2), (2, 3), (3, 1)], [(0, 1), (1, 3), (3, 1)], [(1, 1), (2, 1)]]print(min_distance_sum(graph)) # 输出:4把这段代码转换成c++
以下是将 Python 代码转换为 C++ 的版本:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
typedef pair<int, int> pii;
int prim(vector<vector<pii>>& graph, int start) {
int n = graph.size();
vector<bool> visited(n, false);
vector<int> distance(n, numeric_limits<int>::max());
distance[start] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, start});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
for (auto [v, w] : graph[u]) {
if (!visited[v] && w < distance[v]) {
distance[v] = w;
pq.push({w, v});
}
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += distance[i];
}
return sum;
}
int min_distance_sum(vector<vector<pii>>& graph) {
int n = graph.size();
int min_distance = numeric_limits<int>::max();
for (int i = 0; i < n; i++) {
int distance_sum = prim(graph, i);
min_distance = min(min_distance, distance_sum);
}
return min_distance;
}
int main() {
vector<vector<pii>> graph = {
{{1, 2}, {2, 1}},
{{0, 2}, {2, 3}, {3, 1}},
{{0, 1}, {1, 3}, {3, 1}},
{{1, 1}, {2, 1}}
};
cout << min_distance_sum(graph) << endl; // 输出:4
return 0;
}
```
为这段代码添加中文释义import heapq from collections import defaultdict def huffman_encoding(data): # 计算字符频率 freq = defaultdict(int) for char in data: freq[char] += 1 # 将频率转化为堆 heap = [[weight, [char, ""]] for char, weight in freq.items()] heapq.heapify(heap) # 合并堆中的节点,生成霍夫曼编码树 while len(heap) > 1: low = heapq.heappop(heap) high = heapq.heappop(heap) for pair in low[1:]: pair[1] = '0' + pair[1] for pair in high[1:]: pair[1] = '1' + pair[1] heapq.heappush(heap, [low[0] + high[0]] + low[1:] + high[1:]) # 生成霍夫曼编码表 code_table = dict(heapq.heappop(heap)[1:]) # 编码 encoded_data = "" for char in data: encoded_data += code_table[char] return encoded_data, code_table def huffman_decoding(encoded_data, code_table): # 将编码表反转,方便解码 reverse_code_table = {v: k for k, v in code_table.items()} # 解码 decoded_data = "" code = "" for bit in encoded_data: code += bit if code in reverse_code_table: decoded_data += reverse_code_table[code] code = "" return decoded_data data = "hello world" encoded_data, code_table = huffman_encoding(data) print("Encoded data:", encoded_data) print("Code table:", code_table) decoded_data = huffman_decoding(encoded_data, code_table) print("Decoded data:", decoded_data)
```python
import heapq
from collections import defaultdict
def huffman_encoding(data):
# 计算字符频率
freq = defaultdict(int) # 使用 defaultdict 来实现字符频率的计算
for char in data:
freq[char] += 1
# 将频率转化为堆
heap = [[weight, [char, ""]] for char, weight in freq.items()] # 将频率转化为堆
heapq.heapify(heap)
# 合并堆中的节点,生成霍夫曼编码树
while len(heap) > 1:
low = heapq.heappop(heap)
high = heapq.heappop(heap)
for pair in low[1:]:
pair[1] = '0' + pair[1]
for pair in high[1:]:
pair[1] = '1' + pair[1]
heapq.heappush(heap, [low[0] + high[0]] + low[1:] + high[1:])
# 生成霍夫曼编码表
code_table = dict(heapq.heappop(heap)[1:]) # 生成霍夫曼编码表
# 编码
encoded_data = ""
for char in data:
encoded_data += code_table[char] # 编码数据
return encoded_data, code_table
def huffman_decoding(encoded_data, code_table):
# 将编码表反转,方便解码
reverse_code_table = {v: k for k, v in code_table.items()} # 将编码表反转,方便解码
# 解码
decoded_data = ""
code = ""
for bit in encoded_data:
code += bit
if code in reverse_code_table:
decoded_data += reverse_code_table[code]
code = ""
return decoded_data
data = "hello world"
encoded_data, code_table = huffman_encoding(data)
print("Encoded data:", encoded_data)
print("Code table:", code_table)
decoded_data = huffman_decoding(encoded_data, code_table)
print("Decoded data:", decoded_data)
```
注释已添加,方便理解代码的实现过程。
阅读全文