各种搜索汇总

优先队列BFS和Dijkstra

为什么把这两个放在一起讲,因为这两个特别像;
优先队列每次都把当前已经确定的点中选出一个与原点距离最短的出来然后再把这个玩意用来更新所有没有确定的点;
dijkstra也是这样;

代码:

朴素算法dijkstra:

#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 510;
int n, m, g[N][N], dist[N];
bool st[N];
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[t] > dist[j]))
                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];
}
int main()
{
    scanf("%d%d", &n, &m);
    memset(g, 0x3f, sizeof g);
    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        g[a][b] = min(g[a][b], c);
    }
    printf("%d\n", dijkstra());
    return 0;
}

堆优化dijkstra:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define int long long
const int N=100010,M=1000010;
int head[N],ver[M],edge[M],ne[M],d[N];
bool vis[N];
int n,m,tot;
priority_queue < pair<int,int > >q;

void add(int x,int y,int z){
    ver[++tot]=y;edge[tot]=z;next[tot]=head[x];head[x]=tot;
}

void dijkstra() {
    memset(d,0x3f,sizeof d);
    memset(vis,0,sizeof vis);
    d[1]=0;
    q.make_pair((0,1));
    while(q.size()){
        int x = q.top().second; q.pop();
        if(vis[x])continue;
        vis[x]=1 ;
        for(int i=head[x];i;i=next[i]){
            int y=ver[i],z=edge[i];
            if(d[y] > d[x]+z){
                d[y] = d[x] + z;
                q.push(make_pair(-d[y],y));
            }
        }
    }
}

signed main(){
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int x,y,z;
        scanf("%lld%lld%lld",&x,&y,&z);
        add(x,y,z);
    }
    dijkstra();
    for(int i=1;i<=n;i++){
        printf("%lld\n",d[i]);
    }
    return 0;
}

优先队列的bfs就和这个相似;

上一篇:数据结构与算法(7-4)最短路径(迪杰斯特拉(Dijkstra)算法、弗洛伊德(Floyd)算法)


下一篇:迪杰斯特拉(Dijkstra)算法图解