1. 程式人生 > >演算法模板之次短路

演算法模板之次短路

給你N個點和R條邊,問從起點到終點的次短路是多少。無向邊,且可重複走。

    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <algorithm>
    #define MAXN 100009
    #define INF 0x3f3f3f3f
    using namespace std;
    typedef long long ll;

    struct edge
    {
        int to, cost;
        edge(int tv = 0, int tc = 0):
            to(tv), cost(tc) {}
    };
    typedef pair<ll,ll> P;
    int N, R;
    vector<edge> graph[MAXN];
    ll dist[MAXN];     //最短距離
    ll dist2[MAXN];    //次短距離

    void solve()
    {
        memset(dist, 0x3f, sizeof(dist));
        memset(dist2, 0x3f, sizeof(dist2));
        priority_queue<P, vector<P>, greater<P> > Q;
        dist[1] = 0;
        Q.push(P(0, 1));
        while(!Q.empty())
        {
            P p = Q.top();
            Q.pop();
            int v = p.second;
            ll d = p.first;
            if(dist2[v] < d) continue;
            for(unsigned i = 0; i < graph[v].size(); i++)
            {
                edge &e = graph[v][i];
                ll d2 = d + e.cost;
                if(dist[e.to] > d2)
                {
                    swap(dist[e.to], d2);
                    Q.push(P(dist[e.to], e.to));
                }
                if(dist2[e.to] > d2 && dist[e.to] < d2)
                {
                    dist2[e.to] = d2;
                    Q.push(P(dist2[e.to], e.to));
                }
            }
        }
        printf("%lld\n", dist2[N]);
    }

    int main()
    {
        int A, B, D;
        int t;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d%d", &N, &R);
            for(int i=0;i<=N;i++)
                graph[i].clear();
            for(int i = 0; i < R; i++)
            {
                scanf("%d%d%d", &A, &B, &D);
                graph[A].push_back(edge(B, D));
                graph[B].push_back(edge(A, D));
            }
            solve();
        }
        return 0;
    }
    /*
    Sample Input

    2
    3 3
    1 2 1
    2 3 4
    1 3 3
    2 1
    1 2 1



    Sample Output

    5
    3
    */