HDU 1874 畅通工程续 (最短路模板

来源:互联网 发布:涌泉知恩 编辑:程序博客网 时间:2024/05/16 14:45

畅通工程续

Description

某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。

Input

本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0

Output

对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.

Sample Input

3 30 1 10 2 31 2 10 23 10 1 11 2

Sample Output

2-1

题解:

记住特判不存在的情况

AC代码

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define LL long long#define CLR(a,b) memset(a,(b),sizeof(a))const int INF = 0x3f3f3f3f;const LL INFLL = 0x3f3f3f3f3f3f3f3f;const int N = 1e3+10;int mps[N][N];       //邻接矩阵,表示从->的距离int dis[N];       //dst[i] 从到i的距离bool vis[N];      // 标记节点是否被访问'int n, m;void Dijkstra(int s){    for(int i = 0;i < n; i++) dis[i] = mps[s][i];    dis[s] = 0;    vis[s] = true;    int minx, k;    for(int i = 0;i < n; i++) {        minx = INF;        for(int j = 0;j < n; j++) {            if(!vis[j] && minx>dis[j]) {                minx = dis[j];                k = j;            }        }        if(minx == INF) break;        vis[k] = true;        for(int j = 0; j < n; j++) {            if(!vis[j] && dis[j]>dis[k]+mps[k][j]) {                dis[j] = dis[k]+mps[k][j];            }        }    }}int main(){    while(~scanf("%d%d",&n,&m)) {        CLR(vis,false);        CLR(dis,0);        int x, y, z;        for(int i = 0;i < n; i++) {            for(int j = 0;j < n; j++) {                if(i == j) mps[i][j] = 0;                mps[i][j] = INF;            }        }        for(int i = 0;i < m; i++) {            scanf("%d%d%d",&x,&y,&z);            if(z < mps[x][y])                mps[x][y] = mps[y][x] = z;        }        scanf("%d%d",&x,&y);        Dijkstra(x);        if(dis[y] == INF)            printf("-1\n");        else            printf("%d\n",dis[y]);    }return 0;}