dijkstra + 链式前向星

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <vector>
#define ll long long
#define inf 0x3f3f3f3f
const int maxn = 2e5+7;
using namespace std;
struct node
{
    int to,w,next;
}edge[maxn];
int head[maxn], cnt;
int dis[maxn], vis[maxn];
int n, m, s, t;

void init()
{
    memset(head,-1,sizeof(head));
    memset(dis,0x3f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    cnt = 0;
}

void add(int u,int v,int w)
{
    edge[cnt].to = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt ++;
}

void dijkstra()
{
    dis[s] = 0;
    for(int i = 1; i <= n-1; i++)
    {
        int mi = inf, now;
        for(int j = 1; j <= n; j++) //找离源点最近的一个点
        {
            if(vis[j] == 0 && dis[j] < mi)
            {
                mi = dis[j];
                now = j;  //最近点
            }
        }
        vis[now] = 1; //标记最近点
        for(int i = head[now]; i != -1; i = edge[i].next) //遍历以now为起点的边
        {
            int v = edge[i].to; //v代表以now为起点的边的终点
            if(!vis[v] && dis[v] > dis[now] + edge[i].w) //未标记的情况下能否松弛?
            {
                dis[v] = dis[now] + edge[i].w; //松弛操作
            }
        }
    }
}
int main()
{
    while(~scanf("%d%d",&n,&m) && n+m)
    {
        init(); //初始化
        for(int i = 0; i < m; i++)
        {
            int u, v, w;
            scanf("%d%d%d",&u, &v, &w);
            add(u, v, w);  //加边
            add(v, u, w);
        }
        s = 1, t = n;//s起点,t终点
        dijkstra();
        printf("%d\n",dis[t]);
    }
}

 

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/sugarbliss/article/details/86535929
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞