hdu 1874 (最短路)

畅通工程续

Dijlstra算法:

#include <iostream>

using namespace std;

#define MAX 99999999   

int map[201][201],dis[201];

int mark[201];

int n,m,s,t;

void Dijkstra()

{

       int i , j , k , min ;

       for( i = 0 ; i < n ; i++ )    //初始化距离值,以求点集

       {

              mark[i] = 0 ;    //初始顶点为空,表示没有点加入

              dis[i] = map[s][i] ;   //初始化距离值,每个顶点到起点的距离值

       }

       mark[s] = 1 ;   //标记起点已加入

       /*以为不会求从自己到自己的距离,所以开始时把下面语句写成dis[s]=MAX,WA了很久*/

       dis[s] = 0 ; //标记到起点的距离

       for( i = 1 ; i < n ; i++ )    //寻找其余n-1个点到起点的最短距离

       {

              min = MAX ;

              for( j = 0 ; j < n ; j++ ) //找距离最小的待求点

                     if(!mark[j] && dis[j] < min)

                     {

                            min = dis[j];

                            k = j ;   //k记当前到起点v距离最小的顶点号

                     }

              if(min == MAX)

                     break;

              mark[k] = 1;

              for( j = 0 ; j < n ; j++ )     //调整剩余点的距离值

                     if(!mark[j] && dis[j] > dis[k] + map[k][j])

                            dis[j] = dis[k] + map[k][j] ;

       }

       if(dis[t] != MAX)

              printf("%d\n",dis[t]);

       else

              printf("-1\n");

}

int main()

{

       int i , j , x , y , d ;

       while(scanf("%d %d",&n,&m) != EOF)

       {

              for( i = 0 ; i < n ; i++ ) //初始化map[][]地图为最大值

                     for( j = 0 ; j < n ; j++ )

                            map[i][j] = MAX ;

              for( i = 0 ; i < m ; i++ ) //输入m条道路信息

              {

                     scanf("%d %d %d",&x,&y,&d);

                     if(map[x][y] > d)

                            map[x][y] = map[y][x] = d ;

              }

              scanf("%d %d",&s,&t); //输入起始点和终点

              Dijkstra(); //调用Dijkstra算法求最短路径

       }

       return 0;

}

Flody算法:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

int cost[200][200];

int n,m,i,j,k,maxn,s,t;

int main()

{

       int a,b,x;

    while (scanf("%ld%ld",&n,&m)!=EOF)

    {

        maxn=99999999;

        for (i=0;i<n;i++)

          for (j=0;j<n;j++)

            if (i==j) cost[i][j]=0;

            else cost[i][j]=maxn;      

        for (i=0;i<m;i++)

        {

            scanf("%ld%ld%ld",&a,&b,&x);

            if (x<cost[a][b])

                cost[a][b]=cost[b][a]=x;

        }

        scanf("%ld%ld",&s,&t);

        for (k=0;k<=n-1;k++)

          for (i=0;i<=n-1;i++)

            if (i!=k)

              for (j=0;j<=n-1;j++)

                if (j!=k && i!=j)

                   if (cost[i][j]>cost[i][k]+cost[k][j])

                      cost[i][j]=cost[i][k]+cost[k][j];

        if (cost[s][t]!=maxn) printf("%ld\n",cost[s][t]);

        else printf("-1\n");

    }

    return 0;

}

你可能感兴趣的:(hdu 1874 (最短路))