P6175 无向图的最小环问题
看到这道题,第一个想到的是最短路,想到最短路,先想到的是 ,但是一看好像有点艰难。看看题解发现各路 都用的 ,雀氏很不错,但是
为什么不逝世我们最爱的 呢
算法思路
对于无向图的最小环问题,我们可以这样思考:
环可以看作是从某个点 出发,经过另一个点 ,再回到 的路径
具体来说 形成一个环
其中 是不经过 k 的最短路径
和 是直接相连的边
核心思想:枚举环上的最大编号点 ,在 求最短路时避免经过 ,然后检查所有与 相连的点对 是否能形成环。
其实和 想法差不多(雾
时间复杂度:
空间复杂度 :
##include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const int MAXN = 105;
struct Edge {
int to;
ll weight;
Edge(int t, ll w) : to(t), weight(w) {}
};
struct Node {
int id;
ll dist;
Node(int i, ll d) : id(i), dist(d) {}
bool operator>(const Node& other) const {
return dist > other.dist;
}
};
int n, m;
vector<Edge> graph[MAXN];
ll dist[MAXN];
int pre[MAXN];
bool visited[MAXN];
// Dijkstra 算法,求从 start 出发到其他点的最短距离,跳过 avoid 点
void dijkstra(int start, int avoid) {
for (int i = 1; i <= n; i++) {
dist[i] = INF;
visited[i] = false;
pre[i] = -1;
}
dist[start] = 0;
priority_queue<Node, vector<Node>, greater<Node>> pq;
pq.push(Node(start, 0));
while (!pq.empty()) {
Node current = pq.top();
pq.pop();
int u = current.id;
if (visited[u]) continue;
visited[u] = true;
for (const Edge& e : graph[u]) {
int v = e.to;
// 跳过要避免的点
if (v == avoid) continue;
if (dist[v] > dist[u] + e.weight) {
dist[v] = dist[u] + e.weight;
pre[v] = u;
pq.push(Node(v, dist[v]));
}
}
}
}
int main() {
cin >> n >> m;
// 初始化邻接表
for (int i = 1; i <= n; i++) {
graph[i].clear();
}
// 读入边
for (int i = 0; i < m; i++) {
int u, v, d;
cin >> u >> v >> d;
graph[u].push_back(Edge(v, d));
graph[v].push_back(Edge(u, d));
}
ll min_cycle = INF;
// 枚举环上的最大编号点 k
for (int k = 1; k <= n; k++) {
// 对每个与 k 相连的点 i,求不经过 k 的最短路到其他与 k 相连的点 j
for (const Edge& e1 : graph[k]) {
int i = e1.to;
if (i >= k) continue; // 避免重复计算
// 从 i 出发做 Dijkstra,跳过 k
dijkstra(i, k);
// 检查所有与 k 相连的点 j
for (const Edge& e2 : graph[k]) {
int j = e2.to;
if (j == i || j >= k) continue; // 避免重复和自环
// 如果存在路径 i -> ... -> j 且不经过 k
if (dist[j] != INF) {
// 环的长度 = i->j的最短路 + i->k的边 + j->k的边
ll cycle_length = dist[j] + e1.weight + e2.weight;
min_cycle = min(min_cycle, cycle_length);
}
}
}
}
if (min_cycle != INF) {
cout << min_cycle << endl;
} else {
cout << "No solution." << endl;
}
return 0;
}AI使用说明
代码运用 deepseek 润色