HDU - 1874 畅通工程续(最短路径)

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

s.最短路径

c.Dijkstra单源最短路

/*
Dijkstra单源最短路
权值必须是非负
单源最短路径,Dijkstra算法,邻接矩阵形式,复杂度为O(n^2)
求出源beg到所有点的最短路径,传入图的顶点数,和邻接矩阵cost[][]
返回各点的最短路径lowcost[],路径pre[].pre[i]记录beg到i路径上的父结点,pre[beg]=-1
可更改路径权类型,但是权值必须为非负
*/
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

const int MAXN=256;
#define typec int
const typec INF=0x3f3f3f3f;//防止后面溢出,这个不能太大
bool vis[MAXN];
int pre[MAXN];
void Dijkstra(typec cost[][MAXN],typec lowcost[],int n,int beg){
    for(int i=0;i<n;i++){
        lowcost[i]=INF;vis[i]=false;pre[i]=-1;
    }
    lowcost[beg]=0;
    for(int j=0;j<n;j++){
        int k=-1;
        int Min=INF;
        for(int i=0;i<n;i++)
            if(!vis[i]&&lowcost[i]<Min){
                Min=lowcost[i];
                k=i;
            }
        if(k==-1)break;
        vis[k]=true;
        for(int i=0;i<n;i++)
            if(!vis[i]&&lowcost[k]+cost[k][i]<lowcost[i]){
                lowcost[i]=lowcost[k]+cost[k][i];
                pre[i]=k;
            }
    }
}

int main(){
    int cost[MAXN][MAXN];
    int lowcost[MAXN];

    int N,M;
    int A,B,X;
    int S,T;

    while(~scanf("%d%d",&N,&M)){
        for(int i=0;i<MAXN;++i){
            for(int j=0;j<MAXN;++j){
                cost[i][j]=INF;
            }
        }
        memset(vis,false,sizeof(vis));

        for(int i=0;i<M;++i){
            scanf("%d%d%d",&A,&B,&X);
            if(X<cost[A][B]){//重边。。
                cost[A][B]=cost[B][A]=X;
            }
        }

        scanf("%d%d",&S,&T);
        Dijkstra(cost,lowcost,MAXN,S);

        if(lowcost[T]==INF)printf("-1\n");
        else printf("%d\n",lowcost[T]);
    }
    return 0;
}
View Code

 

posted @ 2015-12-03 21:40  gongpixin  阅读(183)  评论(0编辑  收藏  举报