1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <iostream> #include <algorithm> #include <cstring> using namespace std; const int maxn = 1e3+10; const int maxm = 1e6+10;
int head[maxn],ver[maxm],next1[maxm],dist[maxm]; int dfn[maxn],low[maxn],n,m,tot,num;
int ans;
void add(int x,int y,int v) { ver[++tot] = y; dist[tot] = v; next1[tot] = head[x]; head[x] = tot; }
void tarjan(int x,int in_edge) { dfn[x] = low[x] = ++num; for (int i=head[x]; i; i=next1[i]) { int to = ver[i]; if (!dfn[to]) { tarjan(to,i); low[x] = min(low[x],low[to]); if (low[to] > dfn[x]) { ans = min(ans,dist[i]); ans = min(ans,dist[i^1]); } } else if (i != (in_edge ^ 1)) low[x] = min(low[x],dfn[to]); } }
void init() { ans = 0x3f3f3f3f; memset(head,0,sizeof head); memset(next1,0,sizeof next1); memset(dist,0x3f,sizeof dist); memset(dfn,0,sizeof dfn); memset(low,0,sizeof low); tot = 1; num = 0; }
int main() { freopen("1.in","r",stdin); while (scanf("%d%d",&n,&m) && (n+m)) { init(); for (int i=1; i<=m; ++i) { int x,y,v; cin >> x >> y >> v; add(x,y,v); add(y,x,v); } int flag = 0; for (int i=1; i<=n; ++i) if (!dfn[i]) { flag++; tarjan(i,0); } if (ans == 0x3f3f3f3f) { cout << "-1" << endl; } else if (flag >= 2) cout << "0" << endl; else if (ans == 0) cout << "1" << endl; else cout << ans << endl; } return 0; }
|