hdu-oj 1874 畅通工程续

最短路基础

这个题目hdu-oj 1874可以用来练习最短路的一些算法。

Dijkstra 无优化版本

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define mt memset
using namespace std;
const int maxn = 210;
const int inf = 1<<30;
int N,M;
int mp[maxn][maxn];
int cost[maxn];
bool vis[maxn];
void dijkstra(int s, int t) {
    mt(vis, 0, sizeof(vis));
    for(int i = 0; i < N; i++){
        cost[i] = (i == s? 0 :mp[s][i]);
    }
    vis[s] = true;
    for(int i = 1; i < N; i++) {
        int _min = inf, p = -1;
        for(int j = 0; j < N; j++) {
            if(!vis[j] && _min > cost[j]) {
                _min = cost[j];
                p = j;
            }
        }
        if(p == -1 || _min == inf) continue;//这是重点
        vis[p] = true;
        for(int j = 0; j < N; j++) {
            if(!vis[j] && cost[j] > cost[p]+mp[p][j]) {
                cost[j] = cost[p]+mp[p][j];
            }
        }
    }
}
int main() {
    while(~scanf("%d%d", &N, &M)) {
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < N; j++) {
                mp[i][j] = inf;
            }
        }
        for(int i = 0; i < M; i++) {
            int a, b, x;
            scanf("%d%d%d", &a, &b, &x);
            mp[a][b] = mp[b][a] = min(mp[a][b], x);
        }
        int s,t;
        scanf("%d%d", &s, &t);
        dijkstra(s,t);
        printf("%d
", cost[t] == inf? -1: cost[t]);
    }
    return 0;
}

未优化版的Dijkstra算法时间复杂度为O(n^2)

未完待续...

Focus on Tech & Enjoy Life!

原文地址:https://www.cnblogs.com/yinzm/p/5487339.html