zoukankan      html  css  js  c++  java
  • 【20170706】次短路

    图的次短路(求最短路时顺带求一下):

    #include<iostream>
    #include<vector>
    #include<cstdio>
    #include<queue>
    #define INF 0x7fffffff
    #define Max_v 5005
    using namespace std;
    struct edge{int to,cost;};
    typedef pair<int,int> P;
    int n,m;
    vector <edge> G[Max_v];
    int d[Max_v],d2[Max_v];
    void dijstra(){     
        priority_queue<P,vector<P>,greater<P> >que;
        fill(d+1,d+n+1,INF); fill(d2+1,d2+n+1,INF);
        d[1]=0; que.push(P(0,1));
        while(!que.empty()){
            P p=que.top();que.pop(); 
            int v=p.second,dd=p.first;
            if(d2[v]<dd) continue;
            for(int i=0;i<G[v].size();i++){
                edge e=G[v][i];
                int d_2=dd+e.cost;
                if(d[e.to]==d_2||d_2==d2[e.to]) continue;
                if(d[e.to]>d_2){
                    d2[e.to]=d[e.to];
                    d[e.to]=d_2;
                    que.push(P(d[e.to],e.to));
                    que.push(P(d2[e.to],e.to));
                }
                if(d_2<d2[e.to]&&d_2>d[e.to]){
                    d2[e.to]=d_2;
                    que.push(P(d2[e.to],e.to));
                }
            }
        }
    }
    int main(){
        int x,y,w,minn=INF;
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&x,&y,&w);
            minn=min(minn,w);
            edge e={y,w};
            G[x].push_back(e);
            e={x,w};
            G[y].push_back(e);
        }
        dijstra();
        printf("%d",d2[n]);
        return 0;
    }

    ——————————————————————————————————————

    来自Paper Cloud的博客,未经允许,请勿转载,谢谢。

  • 相关阅读:
    fork()和僵尸进程
    布尔变量面试题
    vue学习之二
    vue学习之一
    圈复杂度
    phpExcel与jq的ajax
    Object.defineProperty与修改某个数组实现监听效果
    mpn不得不说的坑
    论javascript编写优美
    微信小程序之学习
  • 原文地址:https://www.cnblogs.com/PaperCloud/p/7129040.html
Copyright © 2011-2022 走看看