题意
输入N,M,然后输入M条边(u,v,w)表示u-v有一条边权为w的无向边,求w最小的桥,输出w。如果不存在桥输出-1,图不连通输出0。
思路
模板题?就是有两个坑点,①有重边,(重边不算桥)②图不连通输出0
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 5;
const int MAXM = 1e6 + 5;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from, to, w;
Edge (int from, int to, int w): from(from), to(to), w(w) {}
};
struct EdgeBCC//边双联通分量
{
//有重边也算桥的时候,记得先去重再加边!!!
int n, m;
int LOW[MAXN], DFN[MAXN], bccno[MAXN], dfs_clock, bcc_cnt;
bool isbridge[MAXM];
vector<Edge> edges, bridge;
vector<int> G[MAXN];
void init(int n)
{
this->n = n, m = 0;
edges.clear();
for (int i = 0; i <= n; i++) G[i].clear();
}
void AddEdge (int from, int to, int w)
{
edges.push_back(Edge(from, to, w));
edges.push_back(Edge(to, from, w));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
int dfs(int u, int fa)
{
int lowu = DFN[u] = ++dfs_clock;
int child = 0;
bool flag = false;
for (int i = 0; i < G[u].size(); i++)
{
Edge& e = edges[G[u][i]];
int v = e.to;
if (v == fa && !flag) { flag = true; continue; }
if (!DFN[v]) //没有访问过v
{
child++;
int lowv = dfs(v, u);
lowu = min(lowu, lowv); //用后代的low函数更新自己
if (lowv > DFN[u])//桥
{
bridge.push_back(e);
isbridge[G[u][i]] = isbridge[G[u][i]^1] = true;
}
}
else if (DFN[v] < DFN[u])
lowu = min(lowu, DFN[v]); //用反向边更新自己
}
LOW[u] = lowu;
return lowu;
}
void dfs2(int u)
{
bccno[u] = bcc_cnt;
for(int i = 0; i < G[u].size(); i++)
{
Edge e = edges[G[u][i]];
if(!isbridge[G[u][i]] && !bccno[e.to])
dfs2(e.to);
}
}
int find_bcc()
{
memset(DFN, 0, sizeof(DFN)), memset(LOW, 0, sizeof(LOW));
bridge.clear(), memset(bccno, 0, sizeof(bccno));
dfs_clock = bcc_cnt = 0;
int cnt = 0;
for (int i = 0; i < n; i++)
if (!DFN[i]) cnt++, dfs(i, -1);
for(int i = 0; i < n; i++)
if(!bccno[i]) bcc_cnt++, dfs2(i);
return cnt>1?-1:0;
}
}gao;
int n, m;
int main()
{
while (~scanf("%d%d", &n, &m) && (n+m))
{
gao.init(n);
while (m--)
{
int u, v, w; scanf("%d%d%d", &u, &v, &w);
u--, v--;
gao.AddEdge(u, v, w);
}
if (gao.find_bcc() == -1) { printf("0\n"); continue; }
int ans = INF;
for (auto& i: gao.bridge) ans = min(ans, i.w);
if (ans == 0) ans = 1;
if (ans == INF) ans = -1;
printf("%d\n", ans);
}
return 0;
}
/*
3 3
1 2 7
2 3 4
3 1 4
3 2
1 2 7
2 3 4
0 0
*/