Codevs1269 匈牙利遊戲 次短路spfa

來源:互聯網
上載者:User

Codevs1269 匈牙利遊戲

更新時變為3種情況:
1.最短路更新最短路;
2.最短路不能更新最短路但能更新次短路;
3.次短路更新次短路。

思考一下,就顯然了。

#include <cstdio>#include <cstring>#include <iostream>#include <cstdlib>#include <queue>using namespace std;#define MAXN (100100)int V, E, tot = 0;int first[MAXN], nxt[MAXN<<1], dis1[MAXN], dis2[MAXN];bool used[MAXN];struct edge{    int from, to, cost;}es[MAXN<<1];void build(int ff, int tt, int dd){    es[++tot] = (edge){ff,tt,dd};    nxt[tot] = first[ff];    first[ff] = tot;}#define INF (1e9)queue <int> q;void sub_spfa(int s){    fill(dis1+1,dis1+V+1,INF); fill(dis2+1,dis2+V+1,INF);    dis1[s] = 0;    q.push(s);    used[s] = 1;    while(q.size())    {        int x = q.front();        q.pop();        used[x] = 0;        for(int i = first[x]; i != -1; i = nxt[i])        {            int v = es[i].to;            if(dis1[v] > dis1[x] + es[i].cost)            {                dis2[v] = dis1[v];                dis1[v] = dis1[x] + es[i].cost;                if(!used[v])                {                    q.push(v);                    used[v] = 1;                }            }            else if((dis1[v]<dis1[x]+es[i].cost) && (dis2[v]>dis1[x]+es[i].cost))            {                dis2[v] = dis1[x] + es[i].cost;                if(!used[v])                {                    q.push(v);                    used[v] = 1;                }            }            else if(dis2[v] > dis2[x] + es[i].cost)            {                dis2[v] = dis2[x] + es[i].cost;                if(!used[v])                {                    q.push(v);                    used[v] = 1;                }            }         }    }}int main(){    cin >> V >> E;    memset(first,-1,sizeof(first));    for(int i = 1; i <= E; ++ i)    {        int f,t,d;        scanf("%d%d%d", &f, &t, &d);        build(f,t,d);    }    sub_spfa(1);    if(dis2[V] < INF) cout << dis2[V] << '\n';    else puts("-1");    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.