• 畅通工程续


    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
     
    分析:这个题我用的Dijkstra算法,其复杂度为O(n^2),主要思想为:
    (1)找到最短距离已经确定的顶点,从它出发更新相邻顶点的最短距离
    (2)此后不需要再关心1中的“最短距离已经确定的顶点”
    代码如下:
     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 typedef long long ll;
     4 int n,m;
     5 const int inf=1<<30;
     6 int maps[201][201];
     7 int cast[201],vis[201];
     8 void Dijkstra(int s){//给cast数组赋初值 
     9     int pos=s;//将当前点标记为起始点 
    10     vis[s]=1;//标记起点已经走过
    11     for(int i=0;i<n;i++)cast[i]=maps[s][i];//cast数组里存的是起点到各个点的距离
    12     for(int i=1;i<n;i++){//进行n-1次操作,求起点到其他n-1个城市的距离(如果存在) 
    13         int min=inf;
    14         for(int j=0;j<n;j++){
    15             if(cast[j]<min&&!vis[j]){//如果到某个城市距离小于最小值且未曾访问过,则更新 
    16                 min=cast[j];
    17                 pos=j;
    18             }
    19         }
    20         vis[pos]=1;//将目前点标记
    21         for(int j=0;j<n;j++){
    22             if(cast[pos]+maps[pos][j]<cast[j]&&!vis[j])    cast[j]=cast[pos]+maps[pos][j];
    23             //如果连通则更新 
    24         } 
    25     } 
    26 }
    27 int main(){
    28     while(cin>>n>>m){
    29         for(int i=0;i<n;i++){
    30             for(int j=0;j<n;j++){
    31                 if(i==j)    maps[i][j]=0;//先将不同点设置为不连通(无穷大) 
    32                 else maps[i][j]=inf;
    33             }
    34         }
    35         for(int i=0;i<m;i++){
    36             int a,b,x;cin>>a>>b>>x;
    37             if(x<maps[a][b])    maps[a][b]=x;//将道路连接 
    38         }
    39         int startx,endx;
    40         cin>>startx>>endx;
    41          Dijkstra(startx);
    42         printf("%d
    ",cast[endx]==inf?-1:cast[endx]);
    43     }
    44     return 0;
    45 }
  • 相关阅读:
    SQL Serever学习16——索引,触发器,数据库维护
    微信WeUI基础
    SQL Serever学习15——进阶
    SQL Serever学习14——存储过程和触发器
    微信WeUI入门2
    微信WeUI入门
    数据库—索引
    数据库—四种存储引擎
    视图
    事务
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/9463445.html
Copyright © 2020-2023  润新知