Dijkstra's algorithm (no optimization)

Dijkstra's algorithm is a single-source shortest path algorithm, suitable for the case of no negative edge weight

Divided into simple dijkstra O(n^2) (dense graph) and heap-optimized version of dijkstra O(mlogn) (sparse graph)

This article is a simple version of the Dijkstra algorithm template, and the dis[i] array represents the shortest path length from the starting point s to any point.

#include<iostream>
#include<cstring>
using namespace std;
const int inf=0x3f3f3f3f;
int e[1005][1005],dis[1005],vis[1005];
int main()
{
    int n,m,s,t;
    cin>>n>>m>>s>>t;//点数 边数 起点 终点
    memset(e,inf,sizeof(e));
    for(int i=1;i<=n;i++)
        e[i][i]=0;
    int u,v,w;
    for(int i=1;i<=m;i++)
    {
        cin>>u>>v>>w;
        if(e[u][v]>w)
        {
            e[u][v]=w;
            e[v][u]=w;
        }
    }
    memset(dis,inf,sizeof(dis));
    for(int i=1;i<=n;i++)
        dis[i]=e[s][i];
    vis[s]=1;
    for(int i=1;i<n;i++)
    {
        int minn=inf,temp;
        for(int j=1;j<=n;j++)
        {
            if(!vis[j]&&dis[j]<minn)
            {
                minn=dis[j];
                temp=j;
            }
        }
        vis[temp]=1;
        for(int j=1;j<=n;j++)
        {
            if(e[temp][j]+dis[temp]<dis[j])
                dis[j]=e[temp][j]+dis[temp];
        }
    }
    cout<<dis[t]<<endl;;
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_62558103/article/details/124221656