城市问题
Time Limit:10000MS Memory Limit:65536K
Total Submit:242 Accepted:89
Case Time Limit:1000MS
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
Source
elba
var
a:array[0..1000,0..1000]of longint;
l:array[0..1000]of longint;
v:array[0..1000]of boolean;
n,k,i,j,kk:longint;
min:real;
begin
readln(n,k);
k:=k+1;//0到n-1个城市,所以要+1(理论上后面的循环用"0 to n-1"也可以,但是就是错了...)
for i:=1 to n do
begin
for j:=1 to n do
begin
read(a[i,j]);
if a[i,j]=-1 then a[i,j]:=maxlongint;
end;
readln;//换行
end;
fillchar(v,sizeof(v),true);
v[k]:=false;
for i:=1 to n do l[i]:=a[k,i];
for i:=1 to n do
begin
min:=maxlongint;
for j:=1 to n do
if (v[j])and(l[j]<min) then
begin
kk:=j;
min:=l[j];
end;
if kk<>0 then
begin
v[kk]:=false;
for j:=1 to n do
if (v[j])and(l[j]>a[kk,j]+l[kk])and(a[kk,j]<>maxlongint)then l[j]:=l[kk]+a[kk,j];//新条件判断是否连通
end;
end;
for i:=1 to n do
write(l[i],' ');//城市k到各城市间的距离
end.
//详见上一条博客,只改了输入和判断条件(一下水2题的快感~)http://blog.youkuaiyun.com/ssl_lzx/article/details/69261102