2023/5/29-Dijkstra算法优化版

Dijkstra算法优化:通过优先队列实现优化。

模板如下:

void dijkstra(int s) {
   for (int i = 1; i <= n; i++)dist[i] = inf;
    dist[s] = 0;
    //priority_queue < node> q;
    priority_queue, vector >, greater > >q;  //小根堆
    q.push(make_pair(0, s));
    //q.push(node{ 0, s });
    while (!q.empty()) {
        //int x = q.top().pos;
        int x = q.top().second;
        q.pop();
        if (visited[x]) {
            continue;
        }
        visited[x] = 1;
        for (int e = head[x]; e != 0; e = edges[e].next) {
            int v = edges[e].to, w = edges[e].w;
            if (dist[v] > dist[x] + w) {
                dist[v] = dist[x] + w;
                if (!visited[v])
                    q.push(make_pair(dist[v], v));
                    //q.push(node{dist[v],v});
            }
        }
    }

}

优先队列也可以这样定义priority_queue < node> q;需要用到结构体内嵌比较函数,代码如下:

struct node
{
    long long dis;
    int pos;
    bool operator <(const node& x)const  //结构体内嵌比较函数
    {
        return x.dis < dis;
    }
};

P4779 【模板】单源最短路径(标准版) --dijkstra优化版

#include
#include
#include
#include
#include
#include
using namespace std;
const int MAX = 1e5 + 5;
const int MAXN = 2e5 + 5;
#define inf 0x7fffffff
int n, m, s;
long long dist[MAX];
int visited[MAX];
struct Edge {
    int to, w, next;
}edges[MAXN];
int head[MAX];

int cnt;

void add_edges(int u, int v, int w)//加边,u起点,v终点,w边权
{
    edges[++cnt].to = v; //终点
    edges[cnt].w = w; //权值
    edges[cnt].next = head[u];//以u为起点上一条边的编号,也就是与这个边起点相同的上一条边的编号
    head[u] = cnt;//更新以u为起点上一条边的编号
}

//struct node
//{
//    long long dis;
//    int pos;
//    bool operator <(const node& x)const  //结构体内嵌比较函数
//    {
//        return x.dis < dis;
//    }
//};

void dijkstra(int s) {
    for (int i = 1; i <= n; i++)dist[i] = inf;
    dist[s] = 0;
    //priority_queue < node> q;
    priority_queue, vector >, greater > >q;  //小根堆
    q.push(make_pair(0, s));
    //q.push(node{ 0, s });
    while (!q.empty()) {
        //int x = q.top().pos;
        int x = q.top().second;
        q.pop();
        if (visited[x]) {
            continue;
        }
        visited[x] = 1;
        for (int e = head[x]; e != 0; e = edges[e].next) {
            int v = edges[e].to, w = edges[e].w;
            if (dist[v] > dist[x] + w) {
                dist[v] = dist[x] + w;
                if (!visited[v])
                    q.push(make_pair(dist[v], v));
                    //q.push(node{dist[v],v});
            }
        }
    }

}

int main() {
	ios::sync_with_stdio(false);
    cin >> n >> m >> s;
    int u, v, w;
    for (int i = 0; i < m; i++) {
        cin >> u >> v >> w;
        add_edges(u, v, w);
    }
    dijkstra(s);
    for (int i = 1; i <= n; i++)cout << dist[i] << ' ';
	return 0;
}

今天搞到太晚了,先写到这。。。

你可能感兴趣的:(算法)