zoukankan      html  css  js  c++  java
  • hihocoder 1093 SPFA算法

      题目链接:http://hihocoder.com/problemset/problem/1093 , 最短路的SPFA算法。

      由于点的限制(10w),只能用邻接表。今天也学了一种邻接表的写法,感觉挺简单。


      SPFA算法其实就是用了BFS的思想,不过和BFS有所不同,SPFA算法中每个顶点可以多次加入到队列中而BFS只能加入一次。我是参考了别人的博客才弄明白这点,学习了别人的东西就要帮忙传播,附上链接:http://www.cnblogs.com/devtang/archive/2011/08/25/spfa.html 

    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <queue>
    #include <cmath>
    #include <string>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    #define LL __int64
    #define eps 1e-8
    #define INF 1e8
    #define lson l , m , rt << 1
    #define rson m + 1 , r , rt << 1 | 1
    const int MOD = 2333333; 
    const int maxn = 100000 + 5;
    struct Edge {
        int v , w;
    };
    vector <Edge> e[maxn];
    int vis[maxn] , dist[maxn];
    
    void SPFA(int s , int n)
    {
        for(int i = 1 ; i <= n ; i++) {
            dist[i] = INF;
            vis[i] = 0;
        }
        queue <int> que;
        que.push(s);
        dist[s] = 0;
        vis[s] = 1;
        while(!que.empty()) {
            int u = que.front();
            for(int i = 0 ; i < e[u].size() ; i++) {
                int j = e[u][i].v;
                if(dist[u] + e[u][i].w < dist[j]) {
                    dist[j] = dist[u] + e[u][i].w;
                    if(!vis[j]) {
                        que.push(j);
                        vis[j] = 1;
                    }
                }
            }
            que.pop();
            vis[u] = 0;
        }
    }
    int main()
    {
        int n , m , s , t , u , v , w;
        scanf("%d %d %d %d" , &n , &m , &s , &t);while(m--) {
            scanf("%d %d %d" , &u , &v , &w);
            Edge tmp = {v , w};
            e[u].push_back(tmp);
            tmp.v = u;
            e[v].push_back(tmp);
        }
        SPFA(s , n);
        printf("%d
    " , dist[t]);
        return 0;
    }
  • 相关阅读:
    TCP全局同步
    pytest框架之fixture详细使用
    库操作和表操作
    封装之如何隐藏对象及封装的意义
    类的抽象
    组合
    在子类中重用父类的方法和属性
    类的继承和实现原理
    类的使用,对象的使用
    互联网协议的五层协议详解
  • 原文地址:https://www.cnblogs.com/H-Vking/p/4313516.html
Copyright © 2011-2022 走看看