Input
Output
Sample Input
2
3 3
1 2 1
2 3 1
3 1 1
4 5
1 2 2
2 3 2
3 4 2
1 4 2
1 3 5
Sample Output
3
8
Hint
分析
Code
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+5,maxm=4e4+5;
const int Inf=0x3f3f3f3f;
struct Node{int to,next,w;}e[maxm<<1];
int n,m,ans;
int head[maxn],len,dis[maxn];
bool vis[maxn];
priority_queue<pair<int, int> > q;
void Insert(int u,int v,int w){    
    e[len].to=v;e[len].w=w;e[len].next=head[u];head[u]=len++;
}
void Spfa(int x){
    memset(dis,0x3f,sizeof(dis));    
    memset(vis,0,sizeof(vis));
    queue<int> q;
    q.push(x);dis[x]=0;
    while(!q.empty()){
        int u=q.front();q.pop();
        vis[u]=0;
        for(int i=head[u];~i;i=e[i].next){
            int v=e[i].to;
            if(dis[v]>dis[u]+e[i].w){
                dis[v]=dis[u]+e[i].w;
                if(!vis[v]){
                    q.push(v);vis[v]=1;
                }
            }
        }
    } 
}
void Solve(){
    int T;scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&m);
        memset(head,-1,sizeof(head));
        len=0;
        for(int i=1,u,v,w;i<=m;i++){
            scanf("%d%d%d",&u,&v,&w);
            Insert(u,v,w),Insert(v,u,w);
        }
        ans=Inf;
        for(int i=head[1];~i;i=e[i].next){
            int temp=e[i].w;
            e[i].w=e[i^1].w=Inf;//断掉一条邻接边
            Spfa(1);
            ans=std::min(ans,dis[e[i].to]+temp);
            e[i].w=e[i^1].w=temp;//续上
        }
        if(ans==Inf) ans=-1;
        printf("%d\n",ans);       
    }
}
int main(){
    Solve();
    return 0;
}
原文:https://www.cnblogs.com/hbhszxyb/p/13253985.html