zoukankan      html  css  js  c++  java
  • poj3255 次短路的长度

      这道问题是求1-N的次短路的长度,我们直接在dist[maxn][2]上加1维更新即可, 代码如下:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <queue>
    
    using namespace std;
    const int maxn = 5000 + 10;
    
    int N, R;
    struct edge { int v, c; };
    vector<edge> G[maxn];
    
    struct Dij
    {
        int u, flog, c;
        bool operator< (const Dij& r) const
        {
            return c > r.c;
        }
    };
    
    int dist[maxn][2], vis[maxn][2];
    void dijkstra()
    {
        memset(dist, 0x3f, sizeof(dist));
        memset(vis, 0, sizeof(vis));
        dist[1][0] = 0;
        priority_queue<Dij> que;
        que.push((Dij){1, 0, 0});
        while(!que.empty())
        {
            Dij tp = que.top(); que.pop();
            int u=tp.u, flog=tp.flog;
            if(vis[u][flog]) continue;
            vis[u][flog] = 1;
            for(int i=0; i<G[u].size(); i++)
            {
                int v = G[u][i].v, c = G[u][i].c;
                int w = dist[u][flog] + c;
                if(w < dist[v][0])    //更新次短路 最短路
                {
                    if(dist[v][0] != 0x3f3f3f3f)
                    {
                        dist[v][1] = dist[v][0];
                        que.push((Dij){v, 1, dist[v][1]});
                    }
                    dist[v][0] = w;
                    que.push((Dij){v, 0, dist[v][0]});
                }
                else if(w<dist[v][1]) //更新次短路
                {
                    dist[v][1] = w;
                    que.push((Dij){v, 1, dist[v][1]});
                }
            }
        }
    }
    
    int main()
    {
        scanf("%d%d", &N, &R);
        for(int i=0; i<R; i++)
        {
            int u, v, c;
            scanf("%d%d%d", &u, &v, &c);
            G[u].push_back((edge){v, c});
            G[v].push_back((edge){u, c});
        }
        dijkstra();
        printf("%d
    ", dist[N][1]);
        return 0;
    }
  • 相关阅读:
    centos8 安装postresql12
    vs code 开启远程调试步骤
    node 版本管理器 nvs
    Vue I18n Vue.js 的国际化插件+elementUI的使用
    c#结构
    下拉菜单
    使用Convert 类和Parse方法将字符串转换为数值类型
    c# try..... catch
    c#迭代算法
    网页兼容各种浏览器
  • 原文地址:https://www.cnblogs.com/xingxing1024/p/5224499.html
Copyright © 2011-2022 走看看