标签:
3 2 1 2 1 2 3 2 4 3 1 2 1 1 3 2 1 4 3
-1 3
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 10010; 4 const int INF = 0x3f3f3f3f; 5 struct arc{ 6 int to,w,next; 7 arc(int x = 0,int y = 0,int z = -1){ 8 to = x; 9 w = y; 10 next = z; 11 } 12 }e[500000]; 13 int hd[maxn],hd2[maxn],low[maxn],dfn[maxn],belong[maxn],clk,bcc,tot; 14 void add(int *head,int u,int v,int w){ 15 e[tot] = arc(v,w,head[u]); 16 head[u] = tot++; 17 } 18 stack<int>stk; 19 void tarjan(int u,int fa){ 20 dfn[u] = low[u] = ++clk; 21 stk.push(u); 22 bool flag = false; 23 for(int i = hd[u]; ~i; i = e[i].next){ 24 if(e[i].to == fa && !flag){ 25 flag = true; 26 continue; 27 } 28 if(!dfn[e[i].to]){ 29 tarjan(e[i].to,u); 30 low[u] = min(low[u],low[e[i].to]); 31 }else low[u] = min(low[u],dfn[e[i].to]); 32 } 33 if(low[u] == dfn[u]){ 34 int v; 35 ++bcc; 36 do{ 37 v = stk.top(); 38 stk.pop(); 39 belong[v] = bcc; 40 }while(v != u); 41 } 42 } 43 44 int ret = INF,dp[maxn]; 45 void dfs(int u,int fa){ 46 for(int i = hd2[u]; ~i; i = e[i].next){ 47 if(e[i].to == fa) continue; 48 dfs(e[i].to,u); 49 dp[e[i].to] = min(dp[e[i].to],e[i].w); 50 if(dp[u] > dp[e[i].to]){ 51 ret = min(ret,dp[u]); 52 dp[u] = dp[e[i].to]; 53 }else ret = min(ret,dp[e[i].to]); 54 } 55 } 56 void init(){ 57 for(int i = 0; i < maxn; ++i){ 58 hd[i] = hd2[i] = -1; 59 dfn[i] = belong[i] = 0; 60 dp[i] = INF; 61 } 62 tot = bcc = clk = 0; 63 while(!stk.empty()) stk.pop(); 64 } 65 int main(){ 66 int n,m,u,v,w; 67 while(~scanf("%d%d",&n,&m)){ 68 init(); 69 for(int i = 0; i < m; ++i){ 70 scanf("%d%d%d",&u,&v,&w); 71 add(hd,u,v,w); 72 add(hd,v,u,w); 73 } 74 for(int i = 1; i <= n; ++i) 75 if(!dfn[i]) tarjan(i,-1); 76 if(bcc == 1){ 77 puts("-1"); 78 continue; 79 } 80 int minW = INF,id = 0; 81 for(int tt = tot, i = 0; i < tt; i += 2){ 82 if(belong[e[i].to] == belong[e[i^1].to]) continue; 83 add(hd2,belong[e[i].to],belong[e[i^1].to],e[i].w); 84 add(hd2,belong[e[i^1].to],belong[e[i].to],e[i].w); 85 if(e[i].w < minW) minW = e[id = i].w; 86 } 87 ret = INF; 88 dfs(belong[e[id].to],belong[e[id^1].to]); 89 dfs(belong[e[id^1].to],belong[e[id].to]); 90 printf("%d\n",ret == INF?-1:ret); 91 } 92 return 0; 93 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4758666.html