标签:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> #include<vector> using namespace std; #pragma comment(linker, "/STACK:102400000,102400000") #define ls i<<1 #define rs ls | 1 #define pii pair<int,int> #define MP make_pair typedef long long LL; const long long INF = 1e18; const double Pi = acos(-1.0); const int N = 1e4+10, M = 1e5, mod = 1e9+7, inf = 2e9; int ans,scc,t,top,tot,head[N],n,m,dp[N][2],a[N],b[N],c[N]; struct edge{int id,to,next,value;}e[M]; void add(int u,int v,int w) {e[t].next = head[u];e[t].to=v;e[t].value=w;e[t].id=0;head[u]=t++;} int dfn[N],q[N],inq[N],low[N],belong[N],hav[N]; vector<pair<int ,int > > G[N]; void init() { for(int i = 0; i <= n; ++i) dp[i][0] = dp[i][1] = inf; for(int i = 1; i <= n; ++i) G[i].clear(); memset(hav,0,sizeof(hav)); memset(dfn,0,sizeof(dfn)); memset(head,-1,sizeof(head)); t = tot = top = scc = 0; } void dfs(int u) { low[u] = dfn[u] = ++tot; q[++top] = u; inq[u] = 1; for(int i = head[u]; i!=-1; i = e[i].next) { int to = e[i].to; if(e[i].id) continue; e[i].id = e[i ^ 1].id = 1; if(!dfn[to]) { dfs(to); low[u] = min(low[u],low[to]); } else if(inq[to]) low[u] = min(low[u],dfn[to]); } if(low[u] == dfn[u]) { scc++; do{ inq[q[top]] = 0; belong[q[top]] = scc; }while(u != q[top--]); } } void dfs_ans(int u,int fa) { if(u == -1) return ; int fi = 0; for(int i = 0; i < G[u].size(); ++i) { int to = G[u][i].first; int value = G[u][i].second; if(to == fa) continue; dfs_ans(to,u); if(!fi) { dp[u][0] = min(value,dp[to][0]); dp[u][1] = dp[to][1]; fi = 1; } else { if(min(value,dp[to][0]) < dp[u][0]) dp[u][1] = min(dp[u][0],min(dp[to][1],dp[u][1])),dp[u][0] = min(value,dp[to][0]); else dp[u][1] = min(dp[u][1],min(value,dp[to][0])); } } } void Tarjan() { int mi = inf, s = -1, t = -1; for(int i = 1; i <= n; ++i) if(!dfn[i]) dfs(i); for(int i = 1; i <= m; ++i) { int fx = belong[a[i]]; int fy = belong[b[i]]; if(fx != fy) { G[fx].push_back(MP(fy,c[i])); G[fy].push_back(MP(fx,c[i])); // cout<<fx<<" "<<fy<<endl; if(c[i] < mi) { s = fx,t = fy; mi = c[i]; } } } ans = inf; dfs_ans(s,t); dfs_ans(t,s); if(s != -1 && t != -1)ans = min(dp[s][1],dp[t][1]); if(ans == inf) printf("%d\n",-1); else printf("%d\n",ans); } int main() { while(~scanf("%d%d",&n,&m)) { init(); for(int i = 1; i <= m; ++i) { scanf("%d%d%d",&a[i],&b[i],&c[i]); add(a[i],b[i],c[i]);add(b[i],a[i],c[i]); } Tarjan(); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zxhl/p/5951187.html