题意:如标题
思路:tarjan进行缩点,然后各个缩点之间相连的边就是桥了。遍历一下找一下最小值。第一次在无向图中缩点,基本跟有向图差不多。就是为了使同一条边不被遍历两次,用一个flag记录。
PS:这个题有一个巨坑,就是有桥的值为0的时候,应该输出1,结合一下实际。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define clr(x,y) memset(x,y,sizeof x)
#define PI acos(-1.0)
#define ITER set<int>::iterator
const int Mod = 1e9 + 7;
const int maxn = 1e3 + 10;
struct Edge{int to,w,next;}edge[maxn * maxn];
int head[maxn];int edge_num;
int dfn[maxn],low[maxn];int cnt;int ans;
int col[maxn];int st[maxn],top;bool vis[maxn];
void add_edge(int x,int y,int z)
{
edge[edge_num] = (Edge){y,z,head[x]};head[x] = edge_num ++;
edge[edge_num] = (Edge){x,z,head[y]};head[y] = edge_num ++;
}
void Init()
{
clr(head,-1);edge_num = 0;clr(dfn,0);clr(low,0);cnt = 0;ans = INF;clr(col,-1);top = 0;clr(vis,false);
}
void dfs(int u)
{
dfn[u] = 1;
for(int i = head[u];i != -1; i = edge[i].next)
{
if(!dfn[edge[i].to])dfs(edge[i].to);
}
}
void tarjan(int u,int fa,int len)
{
low[u] = dfn[u] = len;st[++ top] = u;vis[u] = true;int flag = false;
for(int i = head[u];i != -1;i = edge[i].next)
{
int v = edge[i].to;
if(v == fa && flag == 0){flag = true;continue;}
if(!dfn[v])
{
tarjan(v,u,++ len);low[u] = min(low[u],low[v]);
}else if(vis[v])low[u] = min(low[u],dfn[v]);
}
if(low[u] == dfn[u])
{
cnt ++;vis[u] = false;col[u] = cnt;
while(st[top --] != u)
{
int x =st[top + 1];vis[x] = false;col[x] = cnt;
}
}
}
struct Node{int to,w;};
vector<Node>g[maxn];
int dfs1(int u,int fa)
{
int ret = INF;
for(int i = 0; i < g[u].size(); i ++)
{
Node e = g[u][i];if(e.to == fa ){continue;}
ret = min(ret,dfs1(e.to,u));ret = min(ret,e.w);
}
return ret;
}
int main()
{
int n,m;
while( ~ scanf("%d%d",&n,&m))
{
if(!n && !m)break;Init();
for(int i = 1; i <= m; i ++)
{
int x,y,z;scanf("%d%d%d",&x,&y,&z);if(x == y)continue;add_edge(x,y,z);
}
int key = 0;
for(int i = 1; i <= n; i ++)if(!dfn[i]){key ++;dfs(i);}
if(key > 1){puts("0");continue;}clr(dfn,0);
for(int i = 1; i <= n;i ++)if(!dfn[i])tarjan(i,-1,0);
if(cnt == 1){puts("-1");continue;}for(int i = 1; i <= cnt; i ++)g[i].clear();
for(int u = 1; u <= n; u ++)
{
for(int i = head[u];i != -1;i = edge[i].next)
{
int v = edge[i].to;
if(col[u] != col[v])
g[col[u]].push_back( (Node){col[v],edge[i].w} );
}
}
ans = dfs1(1,-1);
if(!ans)ans = 1;
printf("%d\n",ans);
}
return 0;
}