1128. 信使

求一遍最大距离即为答案

const int N=110;
vector<PII> g[N];
int dist[N];
bool vis[N];
int n,m;

void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    priority_queue<PII,vector<PII>,greater<PII> > heap;
    heap.push({0,1});
    dist[1]=0;

    while(heap.size())
    {
        int t=heap.top().second;
        heap.pop();

        if(vis[t]) continue;
        vis[t]=true;

        for(int i=0;i<g[t].size();i++)
        {
            int j=g[t][i].fi,w=g[t][i].se;
            if(dist[j] > dist[t] + w)
            {
                dist[j]=dist[t]+w;
                heap.push({dist[j],j});
            }
        }
    }
}

int main()
{
    cin>>n>>m;

    while(m--)
    {
        int a,b,c;
        cin>>a>>b>>c;
        g[a].pb({b,c});
        g[b].pb({a,c});
    }

    dijkstra();
    
    int res=0;
    for(int i=1;i<=n;i++) res=max(res,dist[i]);
    if(res == INF) res=-1;
    cout<<res<<endl;
    
    //system("pause");
}
原文地址:https://www.cnblogs.com/fxh0707/p/13700233.html