迪杰斯特拉算法(最短路径)

参考博客:

https://blog.csdn.net/qq_35644234/article/details/60870719

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 1e6+5;
const int inf = 0x3f3f3f3f;
int n, m, first[maxn], sign;
struct Edge
{
    int to, w, next;
} edge[maxn * 2];
void init()
{
    for(int i = 0; i <=n; i ++ )
        first[i] = -1;
    sign = 0;
}
void add_edge(int u, int v, int w)
{
    edge[sign].to = v;
    edge[sign].w = w;
    edge[sign].next = first[u];
    first[u] = sign ++;
}
struct Node
{
    int to, cost;
    Node() {}
    Node(int tt, int cc):to(tt), cost(cc) {}
    friend bool operator < (const Node &a, const Node &b)
    {
        return a.cost > b.cost;///小先出
    }
};
int dist[maxn], vis[maxn];
int dijkstra(int s, int t)///从s->t的最短路径
{
    for(int i = 0; i <=n; i ++ )
        dist[i] = inf, vis[i] = 0;
    priority_queue<Node>que;
    que.push(Node(s, 0));///将to初始化为s,cost为0

    while(!que.empty())///广度优先搜索
    {
        Node now = que.top();///每次pop出来的cost都是最小的
        que.pop();
        if(!vis[now.to])
        {
            vis[now.to] = 1;
            dist[now.to] = now.cost;///自己到自己是0  所以刚开始cost设置为0
            for(int i = first[now.to]; ~i; i = edge[i].next)///例:把连接1的所有点都看下满足条件否 然后加进去
            {
                int to = edge[i].to, w = edge[i].w;
                if(!vis[to])
                    que.push(Node(to, now.cost + w));///权值相加
            }
        }
    }
    if(dist[t] == inf)
        return -1;
    else
        return dist[t];
}

int main()
{
    int u, v, w;
    while(~scanf("%d %d", &n, &m))
    {
        init();
        for(int i = 0; i <m; i ++ )
        {
            scanf("%d %d %d", &u, &v, &w);
            add_edge(u, v, w);
            add_edge(v, u, w);
        }
        int s, t;
        scanf("%d %d", &s, &t);
        printf("%d\n", dijkstra(s, t));
    }
}

 

posted @ 2018-08-09 17:22  star_fish  阅读(166)  评论(0编辑  收藏  举报