• HDU_1874——最短路问题,Dijkstra算法模版


    Problem Description
    某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。
    现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
     
    Input
    本题目包含多组数据,请处理到文件结束。 每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。 接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。 再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。
     
    Output
    对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
     
    Sample Input
    3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
     
    Sample Output
    2 -1
     1 #include <cstdio>
     2 const int MAX = 10000;
     3 int n,m,map[200][200];
     4 
     5 int Dijkstra(int s,int e)
     6 {
     7     if(s==e)
     8         return 0;
     9     
    10     int mark[200]={0},t;
    11     mark[s]=1;
    12     m=n-1;
    13     while(m--)
    14     {
    15         for(int i=0,min=MAX;i<n;i++)
    16         {
    17             if(!mark[i] && map[s][i]<min)
    18             {
    19                 t=i;
    20                 min=map[s][i];
    21             }
    22         }
    23         mark[t]=1;
    24         for(int i=0;i<n;i++)
    25         {
    26             if(!mark[i] && map[s][t]+map[t][i]<map[s][i])
    27             {
    28                 map[s][i]=map[s][t]+map[t][i];
    29             }
    30         }
    31     }
    32     if(map[s][e]!=MAX)
    33         return map[s][e];
    34     else
    35         return -1;
    36 }
    37 
    38 int main()
    39 {
    40     while(~scanf("%d%d",&n,&m))
    41     {
    42         for(int i=0;i<n;i++)
    43         {
    44             for(int j=0;j<n;j++)
    45             {
    46                 map[i][j]=MAX;
    47             }
    48         }
    49         
    50         int a,b,x;
    51         for(int i=0;i<m;i++)
    52         {
    53             scanf("%d%d%d",&a,&b,&x);
    54             if(x<map[a][b])
    55             {
    56                 map[a][b]=map[b][a]=x;
    57             }
    58         }
    59         
    60         scanf("%d%d",&a,&b);
    61         printf("%d
    ",Dijkstra(a,b));    
    62     }
    63     return 0;
    64 }
    ——现在的努力是为了小时候吹过的牛B!!
  • 相关阅读:
    Flume-NG源码分析-整体结构及配置载入分析
    Flume之核心架构深入解析
    使用maven构建scala项目
    大数据的一些面试题
    HBase原理和设计
    Hive UDAF开发详解
    Hive UDTF开发指南
    Hive UDF开发指南
    局域网访问电脑中VMware虚拟机
    百度面试-前端
  • 原文地址:https://www.cnblogs.com/pingge/p/3198404.html
Copyright © 2020-2023  润新知