城市问题(dij)

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




分析

输入时,如果a[i,j]=-1 那么就a[i,j]=maxlongint

用dijkstra算法,算出每个点之间的最短距离

再一个循环输出


  • var
    n,i,m,s,t,j:longint;
    a:array[0..200,0..200]of longint;
    pre,d:array[0..200]of longint;
    mark:array[0..200]of boolean;
    procedure dij;
    var
    i,j,u,min:longint;
    begin
        for i:=0 to n-1 do
        d[i]:=a[s,i];
        fillchar(mark,sizeof(mark),false);
        mark[s]:=true;
        for j:=0 to n-2 do
        begin
             min:=maxlongint;
             for i:=0 to n-1 do
             if (not mark[i])and(d[i]<min) then
             begin
                 u:=i;
                 min:=d[i];
             end;
             mark[u]:=true;
             for i:=0 to n-1 do
             if (not mark[i])and(d[u]+a[u,i]<d[i])and(a[u,i]<>maxlongint) then
             begin
                 d[i]:=d[u]+a[u,i];
                 pre[i]:=u;
             end;
        end;
    end;
    
    
    begin
        readln(n,s);
        for i:=0 to n-1 do
        for j:=0 to n-1 do
        begin
            read(a[i,j]);
            if a[i,j]=-1 then a[i,j]:=maxlongint;
        end;
        dij;
        for i:=0 to n-1 do
        write(d[i],' ');
    end.
    
    
    


原文地址:https://www.cnblogs.com/YYC-0304/p/9500142.html