城市问题
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
分析
一道简单的最短路模板题,我用的是SPFA
香甜的黄油(SPFA)
AC代码
#include<iostream>
using namespace std;
long long n,k,h,t,k1,tot,d[1005],c[1005],b[10005],head[10005];
struct stu
{
int to,next,w;
}a[10005];
void add(int x,int y,int z)//建立邻接表
{
tot++;
a[tot].to=y;
a[tot].next=head[x];
a[tot].w=z;
head[x]=tot;
}
void spfa(int o)//模板
{
for(int i=1;i<=n;i++)
d[i]=2147483647;
d[o]=0;
c[o]=1;
b[++t]=o;
do
{
h++;
for(int i=head[b[h]];i;i=a[i].next)
if(d[a[i].to]>d[b[h]]+a[i].w)
{
d[a[i].to]=d[b[h]]+a[i].w;
if(c[a[i].to]==0){
b[++t]=a[i].to;c[a[i].to]=1;}
}
c[b[h]]=0;
}while(h<t);
}
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
cin>>k1;
if(k1>0)add(i,j,k1);
}
spfa(k+1);
for(int i=1;i<=n;i++)
cout<<d[i]<<' ';
}