用MATLAB帮我写一个寻找拓扑图中最小权重圈基的算法
- User
用MATLAB帮我写一个寻找拓扑图中最小权重圈基的算法
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
用MATLAB帮我写一个寻找拓扑图中最小权重圈基的算法
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
在图论中,最小权重圈基 (Minimum Weight Cycle Basis) 的寻找是一个经典问题。一个图的圈基是指一个最小的圈集合,使得图中任意一个圈都可以表示为该集合中圈的对称差(异或运算),并且这个集合中的圈是线性无关的。最小权重圈基则是指所有圈基中,圈的权重之和最小的那一个。
Horton 的算法是解决这个问题的标准方法。其核心思想是生成一组“最短圈”作为候选圈,然后通过高斯消元(在GF(2)域上)从中选出权重和最小的圈基。
Horton 算法的步骤概览:
n 个顶点、m 条边和 k 个连通分量的图,其圈空间(cycle space)的维度为 m - n + k。这意味着任何一个圈基都包含 m - n + k 个圈。s,计算从 s 出发的最短路径树 T_s。(u, v):
T_s 中从 s 到 u 的最短路径 P_s(u) 以及从 s 到 v 的最短路径 P_s(v) 共同构成一个圈 C(s, u, v)。P_s(u) \Delta P_s(v) \Delta \{(u,v)\}(对称差运算)得到。n * m 个候选圈。m - n + k 个圈为止。由于是按权重排序后选择的,这保证了选出的圈基的总权重最小。MATLAB 实现考虑的要点:
graph 对象,它提供了方便的函数来处理图,如 numnodes, numedges, shortestpathtree, findedge 等。shortestpathtree(G, s) 可以计算从源 s 到所有其他节点的最短路径树,并返回距离和前驱节点信息。xor 函数可以用于按位异或运算。下面是使用 MATLAB 实现 Horton 算法的代码:
function [basis_cycles, total_weight] = findMinWeightCycleBasis(G)
% findMinWeightCycleBasis 寻找无向加权图的最小权重圈基。
%
% 输入:
% G - MATLAB graph 对象,必须是无向加权图。
% G.Edges.Weight 属性应包含边的权重。
%
% 输出:
% basis_cycles - 包含圈基的元胞数组。每个元胞是一个向量,
% 包含构成该圈的边的索引(Edge ID)。
% total_weight - 圈基中所有圈的权重之和。
% 输入验证
if ~isa(G, 'graph')
error('findMinWeightCycleBasis:InvalidInput', '输入必须是 MATLAB graph 对象。');
end
if isdirected(G)
error('findMinWeightCycleBasis:DirectedGraph', '图必须是无向图。');
end
if isempty(G.Edges) || ~ismember('Weight', G.Edges.Properties.VariableNames)
error('findMinWeightCycleBasis:NoWeights', '图的边必须有权重。');
end
if any(G.Edges.Weight < 0)
warning('findMinWeightCycleBasis:NegativeWeights', '图包含负权重边,Dijkstra 算法可能不适用。请确保所有权重为非负。');
end
n = numnodes(G); % 顶点数量
m = numedges(G); % 边数量
k = numcomponents(G); % 连通分量数量
% 圈空间维度,即圈基的大小
basis_size = m - n + k;
if basis_size <= 0
% 如果图是树或森林,则没有非平凡的圈
basis_cycles = {};
total_weight = 0;
fprintf('图没有非平凡的圈,圈基大小为 %d。\n', basis_size);
return;
end
fprintf('开始寻找最小权重圈基。图有 %d 个顶点,%d 条边,%d 个连通分量。\n', n, m, k);
fprintf('圈基的维度为 %d。\n', basis_size);
% 获取边的信息 (EndNodes 和 Weight)
EdgeTable = G.Edges;
% 使用 containers.Map 存储唯一的候选圈向量,避免重复计算和存储
% Key: 圈向量的字符串表示 (例如 '01100')
% Value: 元胞数组 {该圈的边ID列表, 权重, 该圈的稀疏向量}
unique_cycles_data = containers.Map('KeyType', 'char', 'ValueType', 'any');
fprintf('正在生成候选圈 (Horton 算法)...\n');
% 1. 生成候选圈:对于每个顶点 s,及其最短路径树 Ts。
% 对于图中的每条边 (u, v),将 (u,v) 与 Ts 中 P_s(u) 和 P_s(v) 构成圈。
for s = 1:n
% 计算从 s 出发的最短路径树 (SPT)
% dist_s: 从 s 到各点的距离
% pred: 各点在 SPT 中的前驱节点
[dist_s, ~, pred] = shortestpathtree(G, s);
% 遍历图中的所有边 (edge_idx_uv 是边的索引)
for edge_idx_uv = 1:m
u = EdgeTable.EndNodes(edge_idx_uv, 1);
v = EdgeTable.EndNodes(edge_idx_uv, 2);
% 如果 u 或 v 与 s 相同,或者从 s 无法到达 u 或 v,则跳过
if u == s || v == s || isinf(dist_s(u)) || isinf(dist_s(v))
continue;
end
% 构造从 s 到 u 的路径 P_s(u) 和从 s 到 v 的路径 P_s(v) 的边列表
% 注意:这里必须使用 SPT 中的路径,而不是 G 中的任意最短路径
% shortestpath(G, s, u, 'OutputForm', 'edges') 默认使用Dijkstra,
% 它会找到G中的一条最短路径,这条路径在正权图下是唯一的,也是SPT的一部分
edges_Pu = shortestpath(G, s, u, 'OutputForm', 'edges');
edges_Pv = shortestpath(G, s, v, 'OutputForm', 'edges');
% 将边的ID转换为稀疏二进制向量
vec_Pu = sparse(1, m);
vec_Pu(edges_Pu) = 1;
vec_Pv = sparse(1, m);
vec_Pv(edges_Pv) = 1;
vec_uv = sparse(1, m);
vec_uv(edge_idx_uv) = 1;
% 通过对称差运算 (XOR) 组合路径和边形成圈向量
% 圈 C(s,u,v) = P_s(u) \Delta P_s(v) \Delta {(u,v)}
cycle_vec = xor(xor(vec_Pu, vec_Pv), vec_uv);
% 如果结果向量是全零,说明这不是一个有效的圈(例如,u和v在s的同一条路径上)
if ~any(cycle_vec)
continue;
end
% 将稀疏向量转换为字符串作为 Map 的键,以确保唯一性
% full(cycle_vec) 将稀疏向量转换为完整向量,然后 sprintf 转换为字符串
vec_key = sprintf('%d', full(cycle_vec));
% 如果这个圈向量是新的,则加入到候选列表中
if ~isKey(unique_cycles_data, vec_key)
% 获取构成当前圈的边ID
current_cycle_edge_ids = find(cycle_vec);
% 计算圈的权重
current_cycle_weight = sum(G.Edges.Weight(current_cycle_edge_ids));
% 将圈信息存储到 Map 中
unique_cycles_data(vec_key) = {current_cycle_edge_ids, current_cycle_weight, cycle_vec};
end
end
end
fprintf('生成了 %d 个唯一的候选圈。正在进行基于权重的选择和高斯消元...\n', unique_cycles_data.Count);
% 将 Map 中的数据转换为元胞数组以便排序
all_candidate_items = values(unique_cycles_data); % 元胞数组,每个元素是 {edges, weight, vec}
num_candidates = length(all_candidate_items);
% 预分配空间给候选圈信息和它们的向量
candidate_cycles_info = cell(num_candidates, 2); % {cycle_edges, weight}
candidate_cycle_vectors = sparse(num_candidates, m); % 圈的稀疏二进制向量
% 填充数据
for i = 1:num_candidates
item = all_candidate_items{i};
candidate_cycles_info{i, 1} = item{1}; % 圈的边ID列表
candidate_cycles_info{i, 2} = item{2}; % 圈的权重
candidate_cycle_vectors(i, :) = item{3}; % 圈的稀疏向量
end
% 2. 排序候选圈:按权重从小到大排序
[~, sorted_indices] = sort([candidate_cycles_info{:, 2}]);
sorted_candidate_cycles_info = candidate_cycles_info(sorted_indices, :);
sorted_candidate_cycle_vectors = candidate_cycle_vectors(sorted_indices, :);
% 3. 高斯消元选择圈基 (在GF(2)域上)
basis_cycles = cell(0, 1); % 最终的圈基,存储边ID列表
basis_matrix = sparse(0, m); % 存储已选入基的圈的稀疏向量 (行阶梯形式)
for i = 1:num_candidates
current_cycle_edges = sorted_candidate_cycles_info{i, 1};
current_cycle_vec = sorted_candidate_cycle_vectors(i, :);
% 尝试使用当前的基向量对 current_cycle_vec 进行行简化
% 如果 current_cycle_vec 在简化后非零,则它是线性无关的
for j = 1:size(basis_matrix, 1)
% 找到第 j 个基向量的第一个非零元素(主元)
pivot_col_indices = find(basis_matrix(j,:), 1, 'first');
if isempty(pivot_col_indices)
continue; % 这个基向量是零向量,跳过
end
pivot_col = pivot_col_indices(1);
% 如果当前圈向量在主元列有1,则进行异或操作进行行简化
if current_cycle_vec(pivot_col) == 1
current_cycle_vec = xor(current_cycle_vec, basis_matrix(j,:));
end
end
% 如果简化后的向量不是全零向量,说明它是线性无关的,可以加入基
if any(current_cycle_vec)
basis_cycles{end+1, 1} = current_cycle_edges;
basis_matrix(end+1, :) = current_cycle_vec; % 将简化后的向量加入基矩阵
% 如果已经找到了足够多的圈,就停止
if length(basis_cycles) == basis_size
break;
end
end
end
% 计算最终圈基的总权重
total_weight = 0;
if ~isempty(basis_cycles)
for i = 1:length(basis_cycles)
total_weight = total_weight + sum(G.Edges.Weight(basis_cycles{i}));
end
end
fprintf('成功找到大小为 %d 的最小权重圈基,总权重为 %f。\n', length(basis_cycles), total_weight);
end
如何使用:
创建图对象:
% 示例图 1: 一个简单的三角形
s = [1 2 3]; % 源节点
t = [2 3 1]; % 目标节点
weights = [1 1 1]; % 边的权重
G1 = graph(s, t, weights);
disp(G1.Edges) % 查看图的边及其ID和权重
% 示例图 2: 一个正方形带对角线 (Horton 论文图1)
s2 = [1 2 3 4 1];
t2 = [2 3 4 1 3];
weights2 = [1 1 1 1 1]; % 所有边权重为1
G2 = graph(s2, t2, weights2);
disp(G2.Edges)
调用函数:
% 对示例图 1 调用函数
[basis1, weight1] = findMinWeightCycleBasis(G1);
fprintf('图 G1 的最小权重圈基 (边ID): \n');
for i = 1:length(basis1)
fprintf(' 圈 %d: [', i);
fprintf('%d ', basis1{i});
fprintf('] (权重: %f)\n', sum(G1.Edges.Weight(basis1{i})));
end
fprintf('图 G1 最小权重圈基总权重: %f\n', weight1);
% 对示例图 2 调用函数
[basis2, weight2] = findMinWeightCycleBasis(G2);
fprintf('\n图 G2 的最小权重圈基 (边ID): \n');
for i = 1:length(basis2)
fprintf(' 圈 %d: [', i);
fprintf('%d ', basis2{i});
fprintf('] (权重: %f)\n', sum(G2.Edges.Weight(basis2{i})));
end
fprintf('图 G2 最小权重圈基总权重: %f\n', weight2);
示例输出解释:
图 G1 (三角形):
n=3,边数 m=3,连通分量 k=1。m - n + k = 3 - 3 + 1 = 1。(1-2), (2-3), (3-1) 的圈,总权重为 3。图 G2 (正方形带对角线):
n=4,边数 m=5,连通分量 k=1。m - n + k = 5 - 4 + 1 = 2。(1,2,3,1) (例如,边ID 1,2,5) 权重 3(1,3,4,1) (例如,边ID 5,3,4) 权重 3(1,2,3,4,1) (外圈,边ID 1,2,3,4) 权重 43 + 3 = 6。这个实现提供了一个寻找最小权重圈基的有效方法,适用于中等规模的图。对于非常大的图,计算所有最短路径树和高斯消元的效率可能成为瓶颈。