zoukankan      html  css  js  c++  java
  • SSL 1761——城市问题[最短路]

    Description
      设有n个城市,依次编号为0,1,2,……,n-1(n<=100),另外有一个文件保存n个城市之间的距离(每座城市之间的距离都小于等于1000)。当两城市之间的距离等于-1时,表示这两个城市没有直接连接。求指定城市k到每一个城市i(0<=I,k<=n-1)的最短距离。
    Input
    第一行有两个整数n和k,中间用空格隔开;以下是一个NxN的矩阵,表示城市间的距离,数据间用空格隔开。
    Output
    输出指定城市k到各城市间的距离(从第0座城市开始,中间用空格分开)
    Sample Input
    3 1
    0 3 1
    3 0 2
    1 2 0
    Sample Output
    3 0 2


    由于这只是一个单源最短路,所以用Floyd既耗时又耗空间,so就用dij做。


    代码如下:

    var
      a:array [0..101,0..101] of longint;
      b:array [0..101] of longint;
      f:array [0..101] of boolean;
      n,m,min:longint;
    procedure init;
    var
      i,j:longint;
    begin
      readln(n,m);
      m:=m+1;
      for i:=1 to n do
        for j:=1 to n do
          begin
            read(a[i,j]);
            if a[i,j]=-1 then a[i,j]:=maxlongint;
          end;
    end;
    
    procedure main;
    var
      i,j,t:longint;
    begin
      for i:=1 to n do
        b[i]:=a[m,i];
      fillchar(f,sizeof(f),true);
      f[m]:=false;
      for i:=1 to n-1 do
        begin
          min:=maxlongint;
          for j:=1 to n do
            if f[j] and (b[j]<min) then
              begin
                min:=b[j];
                t:=j;
              end;
          f[t]:=false;
          for j:=1 to n do
            if f[j] and (a[t,j]<>maxlongint) and (b[t]+a[t,j]<b[j]) then
              b[j]:=b[t]+a[t,j];
        end;
      for i:=1 to n do
        write(b[i],' ');
    end;
    
    begin
      init;
      main;
    end.
  • 相关阅读:
    Asp.net web服务处理程序(第六篇)
    Asp.net 处理程序(第五篇)
    HttpApplication实战大文件上传 (第四篇)
    HttpApplication处理对象与HttpModule处理模块 (第三篇)
    Asp.net管道 (第二篇)
    HTTP -> Asp.net (第一篇)
    C# 计划任务
    认识元数据和IL(下)<第五篇>
    认识元数据和IL(中)<第四篇>
    认识元数据和IL(上) <第三篇>
  • 原文地址:https://www.cnblogs.com/Comfortable/p/8412347.html
Copyright © 2011-2022 走看看