最短路之Dijkstra算法模板

复杂度n2,点编号从0到n-1,要对lowcost数组初始化inf , 注意结点编号

const int inf = 0x3f3f3f3f;
const int maxn = 7e3 + 10;
bool vis[maxn];
int pre[maxn], lowcost[maxn];
int cost[maxn][maxn];
void dijkstra(int n, int beg)
{
    for(int i = 0; i < n; ++i)
    {
        lowcost[i] = inf;
        vis[i] = false;
        pre[i] = -1;
    }
    lowcost[beg] = 0;
    for(int j = 0; j < n; ++j)
    {
        int k = -1;
        int Min = inf;
        for(int i = 0; i < n; ++i)
        {
            if(!vis[i] && lowcost[i] < Min)
            {
                Min = lowcost[i];
                k = i;
            }
        }
        if(k == -1)
            break;
        vis[k] = true;
        for(int i = 0; i < n; ++i)
        {
            if(!vis[i] && lowcost[k] + cost[k][i] < lowcost[i])
            {
                lowcost[i] = lowcost[k] + cost[k][i];
                pre[i] = k;
            }
        }
    }
}

 加堆优化,复杂度nlogn,注意:点编号从1开始,对vector<Edge> e[maxn] 进行初始化后加边。

#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 7e3 + 10;
struct node
{
    int v, c;
    bool operator < (const node &r) const
    {
        return c > r.c;
    }
};
struct Edge
{
    int v, cost;
};
vector<Edge> e[maxn];
bool vis[maxn];
int dist[maxn];
void Dijkstra(int n, int start)
{
    memset(vis, false, sizeof(vis));
    for(int i = 1; i <= n; ++i)
        dist[i] = inf;
    priority_queue<node> q;
    while(!q.empty())
        q.pop();
    dist[start] = 0;
    q.push(node{start, 0});
    node tmp;
    while(!q.empty())
    {
        tmp = q.top();
        q.pop();
        int u = tmp.v;
        if(vis[u]) continue;
        vis[u] = true;
        for(int i = 0; i < e[u].size(); ++i)
        {
            int v = e[u][i].v;
            int cost = e[u][i].cost;
            if(!vis[v] && dist[v] > dist[u] + cost)
            {
                dist[v] = dist[u] + cost;
                q.push(node{v, dist[v]});
            }
        }
    }
}
void addedge(int u, int v, int w)
{
    e[u].push_back(Edge{v, w});
}
int main()
{
    int n, m, a, b;
    scanf("%d%d%d%d", &n, &m, &a, &b);
    int u, v, w;
    for(int i = 0; i < maxn; ++i)
        e[i].clear();
    for(int i = 0; i < m; ++i)
    {
        scanf("%d%d%d", &u, &v, &w);
        addedge(u, v, w);
        addedge(v, u, w);
    }
    Dijkstra(n, a);
    //for(int i = 1; i <= n; ++i)
    cout << dist[b] << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/88139235