版权声明:欢迎借鉴,谢绝抄搬。 https://blog.csdn.net/ssllyf/article/details/88069590
城市问题
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
解题思路:
用特判将邻接矩阵换为邻接表,然后SPFA,最后输出
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,s,now,x,w,b[105],p[105],head[105];
struct rec
{
int to,l,next;
}a[10005];
int main()
{
scanf("%d %d",&n,&s);
++s;
for (int i=1;i<=n;++i)
for (int j=1;j<=n;++j)
{
scanf("%d",&x);
if (i==j||x<0) continue;//用一个点或没有直接连接就退出
a[++w].to=j;//邻接表
a[w].l=x;
a[w].next=head[i];
head[i]=w;
}
memset(b,127/3,sizeof(b));
queue<int>d;
d.push(s);
b[s]=0;
p[s]=1;
while (!d.empty())//SPFA
{
now=d.front();
d.pop();
for (int i=head[now];i;i=a[i].next)
if (b[now]+a[i].l<b[a[i].to])
{
b[a[i].to]=b[now]+a[i].l;
if (!p[a[i].to])
{
p[a[i].to]=1;
d.push(a[i].to);
}
}
p[now]=0;
}
for (int i=1;i<=n;++i)//输出
printf("%d ",b[i]);
}