zoukankan      html  css  js  c++  java
  • 图论_最短路

    最短路问题

    image

    Dijkstra

    朴素版Dijkstra

    代码模板
    int dijkstra() {
        memset(dist, 0x3f, sizeof dist);
        dist[1] = 0;
        for(int i = 0; i < n - 1; i++) {
            int t = -1;
            for(int j = 1; j <= n; j++) {
                if(!st[j] && (t == -1 || dist[j] < dist[t])) t = j;
            }
            for(int j = 1; j <= n; j++) {
                dist[j] = min(dist[j], dist[t] + g[t][j]);
            }
            st[t] = true;
    
        }
        if(dist[n] == 0x3f3f3f3f) return -1;
        return dist[n];
    }
    

    堆优化版Dijkstra

    代码模板
    int dijkstra() {
        memset(d, 0x3f, sizeof d);
        d[1] = 0;
        priority_queue<PII, vector<PII>, greater<PII>> heap;
        heap.push({0, 1});
        while(heap.size()) {
            auto t = heap.top();  heap.pop();
            int ver = t.second, dis = t.first;
            if(st[ver]) continue;
            st[ver] = true;
    
            for(int i = h[ver]; i != -1; i = ne[i]) {
                int j = e[i];
                if(d[j] > dis + w[i]) {
                    d[j] = dis + w[i];
                    heap.push({d[j], j});
                }
            }
        }
        if(d[n] == 0x3f3f3f3f) return -1;
        return d[n];
    }
    

    Bellman-Ford算法

    代码模板

    int bellman_ford() {
        memset(d, 0x3f, sizeof d);
        d[1] = 0;
        for(int i = 0; i < k; i++) {
            memcpy(backup, d, sizeof d);
            for(int j = 0; j < m; j++) {
                int a = edges[j].a, b = edges[j].b, c = edges[j].c;
                d[b] = min(d[b], backup[a] + c);
            }
        }
        if(d[n] > 0x3f3f3f3f / 2) return -1;
        return d[n];
    }
    

    Spfa算法

    代码模板

    int spfa() {
        memset(d, 0x3f, sizeof d);
        queue<int> qu;
        d[1] = 0;
        qu.push(1); st[1] = true;
        while(!qu.empty()) {
            int t = qu.front(); qu.pop();
            st[t] = false;
            for(int i = h[t]; i != -1; i = ne[i]) {
                int j = e[i];
                if(d[j] > d[t] + w[i]) {
                    d[j] = d[t] + w[i];
                    if(!st[j]) { 
                        qu.push(j);
                        st[j] = true;
                    }
                }
            }
        }
        if(d[n] == 0x3f3f3f3f) return -1;
        return d[n];
    }
    

    Floyd算法

    代码模板

    void floyd() {
        for(int k = 1; k <= n; k++) 
            for(int i = 1; i <= n; i++) 
                for(int j = 1; j <= n; j++)
                    d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
    }
    
  • 相关阅读:
    MyBatis入门案例、增删改查
    Hibernate第三次测试错题解析
    HIbernate二级缓存
    Hibernate组件映射
    java 序列化
    圈复杂度(Cyclomatic Complexity)
    ASE加、解密
    异常Exception
    动态代理(jdk--cglib)
    java.lang.Class类
  • 原文地址:https://www.cnblogs.com/Hot-machine/p/13198292.html
Copyright © 2011-2022 走看看