图论之最短路径Dijkstra算法

/**
图论之最短路径Dijkstra算法
*/
#include<string.h>
#include<stdio.h>
#include<vector>
#include<queue>

using namespace std;

const int MAXN = 200;
const int INF = 0x7fffffff;
struct Edge
{
    int to ;
    int length;
    Edge(int t, int l):to(t), length(l) {}
};
vector<Edge> graph[MAXN];
int dis[MAXN];
bool visit[MAXN];

void Dijkstra (int start, int n)
{
    memset(visit, false, sizeof(visit));
    fill(dis, dis+n, INF);
    dis[start] = 0;

    for(int i=0;i<n;i++)
    {
        int u=-1;
        for(int j=0;j<n;j++)
        {
            if(visit[j]) continue;
            if(u == -1 || dis[j]<dis[u])
            {
                u = j;
            }

        }
        for(int j=0;j<graph[u].size();j++)
        {
            int v = graph[u][j].to;
            int d = graph[u][j].length;
            if(dis[u] + d < dis[v])
            {
                dis[v] = dis[u] + d;
            }
        }
        visit[u] = true;
    }
    return ;
}
int main ()
{
    int n,m;
    scanf("%d%d",&n,&m);
    memset(graph, 0, sizeof(graph));
    while(m--)
    {
        int from, to, length;
        scanf("%d%d%d", &from, &to, &length);
        graph[from].push_back(Edge(to, length));
        graph[to].push_back(Edge(from, length));
    }
    int start, terminal;
    scanf("%d%d",&start, &terminal);
    Dijkstra(start, n);
    if(dis[terminal] == INF)
    {
        dis[terminal] = -1;
    }
    printf("%d\n",dis[terminal]);
    return 0;
}
/**
3 3
0 1 1
0 2 3
1 2 1
0 2
输出2
3 1
0 1 1
1 2
输出-1
*/

 

上一篇:heap优化dijkstra


下一篇:算法工程师必备精选文章50篇