算法详细思路
1. 问题定义与核心思想
问题定义:在带权有向图中,寻找所有节点标签序列与给定模式字符串匹配的路径,并按路径权重进行排序。
核心思想:融合三种算法的优势:
- Z-algorithm:提供高效的模式匹配能力
- Johnson算法:处理带权图的路径重构和权重计算
- Countingsort:对结果进行线性时间排序
2. 算法阶段分解
阶段1:Johnson风格的图预处理
// 伪代码说明
JohnsonStyleReweight(G):
添加虚拟源节点s,连接所有节点,权重为0
使用Bellman-Ford计算从s到所有节点的最短路径h
重新赋权:w'(u,v) = w(u,v) + h[u] - h[v]
返回重构后的图G'和势能函数h目的:
- 消除负权边的影响
- 保证重新赋权后所有边权非负
- 保持最短路径的相对顺序不变
阶段2:基于Z-algorithm的模式匹配
// 伪代码说明
PatternMatching(G, pattern):
对于每个起始节点:
进行深度优先搜索(DFS)
在DFS过程中构建路径标签序列
使用Z-algorithm检查当前路径是否匹配模式
记录匹配的路径及其权重Z-algorithm匹配原理:
- 构建组合字符串:
pattern + '$' + current_path - 计算Z数组:Z[i]表示从位置i开始的最长匹配前缀长度
- 如果存在Z[i] = pattern.length(),则找到匹配
阶段3:计数排序优化
// 伪代码说明
CountingsortPaths(paths):
计算所有路径权重的最大值max_weight
创建计数数组count[0..max_weight]
统计每个权重的路径数量
计算累积频率
按权重排序路径3. 算法复杂度分析
- Johnson预处理:O(VE) - 使用Bellman-Ford
- 模式匹配:O(n × k × L) - n为节点数,k为平均度数,L为模式长度
- 计数排序:O(n + k) - n为路径数,k为权重范围
C++完整实现
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <limits>
#include <algorithm>
#include <stack>
#include <utility>
using namespace std;
class ZJohnsonCountingsort {
private:
// 图结构:邻接表表示
unordered_map<int, vector<pair<int, int>>> graph;
// 节点标签映射
unordered_map<int, char> node_labels;
// 虚拟源节点ID
static const int VIRTUAL_SOURCE = -1;
public:
// 添加边
void addEdge(int u, int v, int weight, char u_label, char v_label) {
graph[u].emplace_back(v, weight);
node_labels[u] = u_label;
node_labels[v] = v_label;
}
// Z-algorithm实现
vector<int> computeZ(const string& s) {
int n = s.length();
vector<int> z(n, 0);
int l = 0, r = 0;
for (int i = 1; i < n; i++) {
if (i <= r) {
z[i] = min(r - i + 1, z[i - l]);
}
while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
z[i]++;
}
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
// 检查路径是否匹配模式
bool zAlgorithmMatch(const string& text, const string& pattern) {
string combined = pattern + "$" + text;
vector<int> z = computeZ(combined);
for (int i = pattern.length() + 1; i < combined.length(); i++) {
if (z[i] == pattern.length()) {
return true;
}
}
return false;
}
// Johnson风格的图重构
pair<unordered_map<int, vector<pair<int, int>>>, unordered_map<int, int>>
johnsonStyleReweight() {
// 添加虚拟源节点
unordered_map<int, vector<pair<int, int>>> graph_prime = graph;
graph_prime[VIRTUAL_SOURCE] = {};
for (const auto& node : graph) {
graph_prime[VIRTUAL_SOURCE].emplace_back(node.first, 0);
}
// Bellman-Ford计算势能函数h
unordered_map<int, int> h;
for (const auto& node : graph_prime) {
h[node.first] = numeric_limits<int>::max() / 2;
}
h[VIRTUAL_SOURCE] = 0;
// Bellman-Ford算法
for (int i = 0; i < graph_prime.size() - 1; i++) {
for (const auto& u_nodes : graph_prime) {
int u = u_nodes.first;
for (const auto& edge : u_nodes.second) {
int v = edge.first;
int w = edge.second;
if (h[u] != numeric_limits<int>::max() / 2 && h[u] + w < h[v]) {
h[v] = h[u] + w;
}
}
}
}
// 重新赋权
unordered_map<int, vector<pair<int, int>>> reweighted_graph;
for (const auto& u_nodes : graph) {
int u = u_nodes.first;
reweighted_graph[u] = {};
for (const auto& edge : u_nodes.second) {
int v = edge.first;
int w = edge.second;
int new_w = w + h[u] - h[v];
reweighted_graph[u].emplace_back(v, new_w);
}
}
return {reweighted_graph, h};
}
// 计算路径距离
int calculatePathDistance(const unordered_map<int, vector<pair<int, int>>>& g,
const vector<int>& path) {
int distance = 0;
for (size_t i = 0; i < path.size() - 1; i++) {
int u = path[i];
int v = path[i + 1];
bool found = false;
for (const auto& edge : g.at(u)) {
if (edge.first == v) {
distance += edge.second;
found = true;
break;
}
}
if (!found) {
return numeric_limits<int>::max(); // 路径不连续
}
}
return distance;
}
// 模式匹配搜索
vector<pair<vector<int>, int>> findPatternOccurrences(
const unordered_map<int, vector<pair<int, int>>>& g,
const string& pattern) {
vector<pair<vector<int>, int>> occurrences;
for (const auto& start_node : g) {
int start = start_node.first;
if (start == VIRTUAL_SOURCE) continue;
// 使用DFS搜索所有可能路径
stack<pair<int, vector<int>>> dfs_stack;
dfs_stack.push({start, {start}});
while (!dfs_stack.empty()) {
auto [current_node, current_path] = dfs_stack.top();
dfs_stack.pop();
// 构建路径标签字符串
string path_labels;
for (int node_id : current_path) {
path_labels += node_labels[node_id];
}
// 检查路径长度
if (current_path.size() == pattern.length()) {
if (zAlgorithmMatch(path_labels, pattern)) {
int distance = calculatePathDistance(g, current_path);
if (distance != numeric_limits<int>::max()) {
occurrences.emplace_back(current_path, distance);
}
}
continue;
}
// 继续搜索
if (g.find(current_node) != g.end()) {
for (const auto& edge : g.at(current_node)) {
int neighbor = edge.first;
// 避免重复节点(可根据需求修改)
if (find(current_path.begin(), current_path.end(), neighbor) == current_path.end()) {
vector<int> new_path = current_path;
new_path.push_back(neighbor);
dfs_stack.push({neighbor, new_path});
}
}
}
}
}
return occurrences;
}
// 计数排序路径
vector<pair<vector<int>, int>> countingsortByDistance(
const vector<pair<vector<int>, int>>& occurrences) {
if (occurrences.empty()) return {};
// 找到最大距离
int max_distance = 0;
for (const auto& occ : occurrences) {
max_distance = max(max_distance, occ.second);
}
// 计数
vector<int> count(max_distance + 1, 0);
for (const auto& occ : occurrences) {
count[occ.second]++;
}
// 计算累积频率
for (int i = 1; i <= max_distance; i++) {
count[i] += count[i - 1];
}
// 排序
vector<pair<vector<int>, int>> sorted(occurrences.size());
for (int i = occurrences.size() - 1; i >= 0; i--) {
int pos = count[occurrences[i].second] - 1;
sorted[pos] = occurrences[i];
count[occurrences[i].second]--;
}
return sorted;
}
// 主算法入口
vector<pair<vector<int>, int>> zJohnsonCountingsort(const string& pattern) {
// 阶段1: Johnson风格图重构
auto [reweighted_graph, h] = johnsonStyleReweight();
// 阶段2: 模式匹配
auto occurrences = findPatternOccurrences(reweighted_graph, pattern);
// 阶段3: 计数排序
auto sorted_results = countingsortByDistance(occurrences);
return sorted_results;
}
// 打印结果
void printResults(const vector<pair<vector<int>, int>>& results) {
cout << "Found " << results.size() << " matching paths:" << endl;
for (size_t i = 0; i < results.size(); i++) {
cout << "Path " << i + 1 << " (Distance: " << results[i].second << "): ";
for (int node : results[i].first) {
cout << node_labels[node] << "(" << node << ") ";
}
cout << endl;
}
}
};
// 测试示例
int main() {
ZJohnsonCountingsort zjc;
// 构建测试图
// 节点: 0-A, 1-B, 2-C, 3-D
zjc.addEdge(0, 1, 2, 'A', 'B'); // A->B, weight=2
zjc.addEdge(0, 2, 1, 'A', 'C'); // A->C, weight=1
zjc.addEdge(1, 2, 3, 'B', 'C'); // B->C, weight=3
zjc.addEdge(1, 3, 4, 'B', 'D'); // B->D, weight=4
zjc.addEdge(2, 3, 2, 'C', 'D'); // C->D, weight=2
zjc.addEdge(2, 0, 1, 'C', 'A'); // C->A, weight=1 (环)
// 搜索模式"ABC"
string pattern = "ABC";
auto results = zjc.zJohnsonCountingsort(pattern);
cout << "Pattern: " << pattern << endl;
zjc.printResults(results);
return 0;
}图模式匹配与排序的实际意义
1. 算法优势
- 精确匹配:Z-algorithm确保模式匹配的准确性
- 权重处理:Johnson方法处理复杂权重关系
- 高效排序:计数排序提供线性时间性能
- 灵活性:支持带权图、负权边等复杂场景
2. 扩展应用
该算法可扩展用于:
- 时序图分析:时间序列中的模式发现
- 多模态网络:处理包含多种类型节点的异质图
- 动态图:实时图数据的模式监控
- 近似匹配:支持容错的模式搜索
这个算法为图数据分析提供了一个强大的工具,特别适用于需要精确模式匹配和高效排序的复杂网络分析任务。