常用最短路算法汇总

常用最短路算法汇总

在这里插入图片描述

朴素Dijkstra算法

稠密图时使用(稠密图采用邻接矩阵来存储)

代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int n,m;
const int N = 510;
int g[N][N];
int dis[N];
int st[N];


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

int main()
{
    memset(g, 0x3f, sizeof g);
    cin >> n >> m;
    while(m --){
        int a, b, c;
        cin >> a >> b >> c;
        // 有平行边,取最短的
        g[a][b] = min(g[a][b],c);
        
    }

    int t = dijkstra();
    
    printf("%d\n",t);
    
    return 0;
}

堆优化版的Dijkstra算法

堆可以直接用O(1)的复杂度取得最小的值,所以如果对于稀疏图,可以采用堆优化版的Diujkstra算法

存储方式因为时稀疏图所以采用邻接表存储

代码

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

typedef pair<int,int> PII;

int n,m;
const int N = 100010 * 2;
int h[N],w[N],e[N],ne[N],idx;
int dist[N];
bool st[N];

void add(int a,int b,int c){
    e[idx] = b,w[idx] = c,ne[idx] = h[a],h[a] = idx ++;
}

int dijkstra(){

    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    priority_queue<PII,vector<PII>,greater<PII>> heap;
    heap.push({0,1});

    while(heap.size()){
        PII t = heap.top();
        heap.pop();

        int ver = t.second, distance = t.first;
        if(st[ver]) continue;
        st[ver] = true;

        for(int i = h[ver];i != -1;i = ne[i]){
            int j = e[i];
            if(dist[j] > w[i] + distance){
                dist[j] = w[i] + distance;
                heap.push({dist[j],j});
            }
        }

    }

    if(dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];

}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    while(m --){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }

    printf("%d",dijkstra());
    return 0;
}

Bellman-ford算法

该算法就是类似于枚举,经过n次松弛操作,每一次将从起点到其它点的距离进行松弛

解决存在负权边的问题

代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 510, M = 100010;
int dist[N],backup[N];

struct Edge {
    int a, b, w;
}edges[M];

int n,m,k;

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

int main()
{
    
    cin >> n >> m >> k;
    for(int i = 0;i < m;i ++){
        int a, b, w;
        scanf("%d%d%d",&a,&b,&w);
        edges[i] = {a, b, w};
    }
    
    int t = bellman_ford();
    if(t == -1) puts("impossible");
    else printf("%d\n",t);
    return 0;
}

SPFA(队列优化的bellman-ford)算法

bellman-ford算法的队列优化就是将已经更新的节点放入队列,因为如果节点未更新,那么对后序以该节点为中转的路径最短不会更新,所以不必要重复判断

代码

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 100010;
int h[N],w[N],e[N],ne[N],idx;
int dist[N];
bool st[N];
int n,m;

void add(int a, int b, int c){
    e[idx] = b,w[idx] = c,ne[idx] = h[a],h[a] = idx ++;
}

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

int main()
{
    memset(h, -1, sizeof h);
    scanf("%d%d",&n,&m);
    while(m --){
        int a, b, c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    
    int t = spfa();
    
    if(t == -1) puts("impossible");
    else printf("%d\n",t);
    return 0;
}

Floyd求多源最短路径

floyd求最短路径基于动态规划,思想就是遍历所有点,以该点为中心点,枚举所有两个顶点,是否能通过中心点达到路径减小

代码

#include <iostream>
#include <cstring>
using namespace std;

int n, m, Q;
const int N = 210,INF = 1e9;
int d[N][N];

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]);
            }
        }
    }

}

int main()
{
    scanf("%d%d%d",&n,&m,&Q);

    for(int i = 1;i <= n;i ++){
        for(int j = 1;j <= n;j ++){
            if(i == j) d[i][j] = 0;
            else d[i][j] = INF;
        }
    }

    while(m --){
        int a, b, c;
        scanf("%d%d%d",&a,&b,&c);
        d[a][b] = min(d[a][b],c);
    }

    floyd();

    while(Q --){
        int a, b;
        scanf("%d%d",&a,&b);
        if(d[a][b] > INF / 2) puts("impossible");
        else printf("%d\n",d[a][b]);
    }
    return 0;
}
### 常见算法题笔试总结与快速参考 对于参加技术面试或编程竞赛的人来说,掌握一些常见的算法及其应用是非常重要的。以下是关于算法题笔试的一些常见知识点和技巧汇总: #### 一、基础算法分类及特点 1. **排序算法** 排序问题是算法基本的一类问题之一。常用的排序算法有冒泡排序、插入排序、选择排序、快速排序等。其中,快速排序因其平均时间复杂度为 \(O(n \log n)\),成为实际应用中的首选[^1]。 2. **查找算法** 查找算法主要包括线性查找、二分查找等。二分查找适用于有序数组,在佳情况下可以达到 \(O(\log n)\) 的时间复杂度。 3. **动态规划 (Dynamic Programming, DP)** 动态规划是一种通过把原问题分解为相对简单的子问题的方式来解复杂问题的方法。它通常用于解决具有重叠子问题和优子结构性质的问题。例如背包问题、长公共子序列(LCS)等问题都可以用DP来高效解决。 4. **贪心算法** 贪心算法总是做出当前看来好的选择,希望以此得到全局优解。虽然这种方法并不总能给出优化的结果,但在某些特定条件下却非常有效,比如霍夫曼编码、小生成树(Kruskal 和 Prim 算法)。 5. **图论算法** 图论涉及节点之间的关系建模,广泛应用于社交网络分析等领域。经典算法包括广度优先搜索(BFS)、深度优先搜索(DFS)、Dijkstra 短路算法以及 Floyd-Warshall 多源短路算法等。 #### 二、常用数据结构概览 - 队列(Queue): FIFO 结构,适合模拟排队过程。 - 栈(Stack): LIFO 结构,可用于括号匹配检测等功能实现。 - 堆(Heap): 是一种特殊的完全二叉树形式的数据结构,分为大堆和小堆两种类型;主要用于实现优先队列(Priority Queue)功能。 - 字典树(Trie Tree): 对于字符串集合操作特别有用的一种多叉树形结构。 #### 三、代码模板实例展示 下面提供几个典型算法的Python版本简单实现作为示范: ```python # 快速排序函数定义 def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[len(arr)//2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left)+middle+quick_sort(right) # 测试输入列表并调用上述方法对其进行升序排列 test_list=[8,7,6,5,4,3,2,1] sorted_result=quick_sort(test_list) print(sorted_result) # 斐波那契数列递推计算方式 def fibonacci_dp(n): fibs={0:0,1:1} for i in range(2,n+1): fibs[i]=fibs[i-1]+fibs[i-2] return fibs[n] result=fibonacci_dp(10) print(result) ``` 以上仅为部分精选内容摘录,更多深入细节可查阅相关资料获取完整的PDF文档或者Cheat Sheet文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值