• 基础最短路(模板 dijkstra)


    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<iostream>
     2 # include<cstdio>
     3 # include<algorithm>
     4 # include<cstring>
     5 # include<queue>
     6 using namespace std;
     7 const int INF=1<<30;
     8 /*struct edge
     9 {
    10     int fr,to,w,nxt;
    11 };
    12 edge e[2010];
    13 int head[205];*/
    14 int mp[205][205],d[205],n,m,vis[205];
    15 void dijkstra(int s)
    16 {
    17     int i,j;
    18     fill(d,d+n,INF);
    19     fill(vis,vis+n,0);
    20     d[s]=0;
    21     vis[s]=1;
    22     queue<int>q;
    23     q.push(s);
    24     while(!q.empty()){
    25         int u=q.front();
    26         q.pop();
    27         for(i=0;i<n;++i){
    28             if(mp[u][i]!=INF&&!vis[i]&&d[i]>d[u]+mp[u][i]){
    29                 d[i]=d[u]+mp[u][i];
    30                 q.push(i);
    31             }
    32         }
    33     }
    34 }
    35 int main()
    36 {
    37     int s,t,i,j,a,b,c;
    38     while(scanf("%d%d",&n,&m)!=EOF)
    39     {
    40         for(i=0;i<n;++i)
    41             for(j=0;j<n;++j)
    42                 mp[i][j]=INF;
    43         for(i=1;i<=m;++i){
    44             scanf("%d%d%d",&a,&b,&c);
    45             mp[a][b]=mp[b][a]=min(mp[a][b],c);
    46         }
    47         scanf("%d%d",&s,&t);
    48         dijkstra(s);
    49         if(d[t]==INF)
    50             printf("-1
    ");
    51         else
    52             printf("%d
    ",d[t]);
    53     }
    54     return 0;
    55 }
    View Code 
  • 相关阅读:
    Java基础面试题总结
    mysql面试题总结
    记7.9面试题
    深入理解Java虚拟机学习笔记(三)-----类文件结构/虚拟机类加载机制
    jvm类加载子系统
    多线程与高并发基础三
    多线程与高并发基础二
    多线程与高并发基础一
    多线程与高并发笔记一
    Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property.
  • 原文地址:https://www.cnblogs.com/20143605--pcx/p/4677182.html
Copyright © 2020-2023  润新知