zoukankan      html  css  js  c++  java
  • dijkstra最短路算法--模板

    input

    输入n,m,k分别代表城市个数,路的条数,和要求城市

    然后输入m跳路,ai,bi,ci表示城市ai到城市bi的距离是ci

    output

    求每个城市到城市k的距离

    input

    6 9 1
    1 2 1
    1 3 12
    2 3 9
    2 4 3
    3 5 5
    4 3 4
    4 5 13
    4 6 15
    5 6 4
    ******************
    6 9 2
    1 2 1
    1 3 12
    2 3 9
    2 4 3
    3 5 5
    4 3 4
    4 5 13
    4 6 15
    5 6 4
    output
    0 1 8 4 13 17
    *****************
    inf 0 7 3 12 16
    模板代码:
     1 #include <iostream>
     2 #include <cstdio>
     3 #define MAX 1e9+100
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     int n,m,a,b,c,k,u,dis[10];
     9     int s[10][10],book[10];
    10     while(~scanf("%d%d%d",&n,&m,&k))
    11     {
    12         for(int i=1;i<=n;i++)
    13         {
    14             book[i]=0;
    15             for(int j=1;j<=n;j++)
    16             if(i==j)
    17             s[i][j]=0;
    18             else
    19             s[i][j]=MAX;
    20         }
    21         for(int i=0;i<m;i++)
    22         {
    23             scanf("%d%d%d",&a,&b,&c);
    24             s[a][b]=c;
    25         }
    26         for(int i=1;i<=n;i++)
    27         dis[i]=s[k][i];
    28         book[k]=1;
    29         for(int i=1;i<=n-1;i++)
    30         {
    31             int min=MAX;
    32             for(int j=1;j<=n;j++)
    33             {
    34                 if(book[j]==0&&dis[j]<min)
    35                 {
    36                     min=dis[j];
    37                     u=j;
    38                 }
    39             }
    40             printf("%d
    ",u);
    41             book[u]=1;
    42             for(int v=1;v<=n;v++)
    43             {
    44                 if(s[u][v]<MAX)
    45                 {
    46                     if(dis[v]>dis[u]+s[u][v])
    47                     dis[v]=dis[u]+s[u][v];
    48                 }
    49             }
    50         }
    51         for(int i=1;i<=n;i++)
    52         printf("%d ",dis[i]);
    53         getchar();
    54         printf("
    ");
    55     }
    56     return 0;
    57 }
    View Code

    参考博客:http://www.cnblogs.com/ahalei/p/3635090.html

  • 相关阅读:
    pip install selenium==版本号 报错
    解决phantomjs输出中文乱码
    phantomjs学习之网页访问测速
    phantomjs学习之截图
    bzoj1069-最大土地面积
    hdu4372-Count the Buildings
    bzoj3786-星系探索
    Codeforces633H-Fibonacci-ish II
    hdu3625-Rooms
    斯特林数
  • 原文地址:https://www.cnblogs.com/wang-ya-wei/p/5733402.html
Copyright © 2011-2022 走看看