城市问题

城市问题

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

恶心的题目数据,点10范围超大!
这是一道模板题,我就不多说了

code:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int b[15000000],t=0,head[1500000],dis[15000000],f[15000000],z[15000000];
struct node
{
	int x,y,next,zz;
}a[1500000];
void add(int xx,int yy,int sum)  
{
	a[++t].x=xx;
	a[t].y=yy;
	a[t].next=head[xx];
	a[t].zz=sum;
	head[xx]=t;
}
void spfa(int x) 
{
	memset(z,0x7f,sizeof(z));
	dis[x]=1;
	int h=0,t=1;
	f[1]=x;
	z[x]=0;
	do
	{
		h++; 
		int tx=f[h];
		for(int i=head[tx];i;i=a[i].next)
		{
			if(z[a[i].y]>z[tx]+a[i].zz)
			{
				z[a[i].y]=z[tx]+a[i].zz;
				if(dis[a[i].y]==0){
					t++;
					dis[tx]=1;
					f[t]=a[i].y;
				}
			}
		}
		dis[tx]=0;
	}while(h<t); 
}
int main()
{
	int n,a,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>a;
			if(a==-1) continue;
			add(i,j,a);
		}
	}
	spfa(k+1);
	for(int i=1;i<=n;i++) cout<<z[i]<<' ';
	cout<<endl;
	return 0;
}

谢谢

发布了81 篇原创文章 · 获赞 59 · 访问量 2560

猜你喜欢

转载自blog.csdn.net/bigwinner888/article/details/104005779