【图论】【Floyed】商店选址问题 (ssl 1760)

D e s c r i p t i o n Description

给出一个城市的地图(用邻接矩阵表示),商店设在一点,使各个地方到商店距离之和最短。

I n p u t Input

第一行为n(共有几个城市);
第二行至第n+1行为城市地图(用邻接矩阵表示);

O u t p u t Output

最短路径之和;

S a m p l e I n p u t Sample Input

3
0 3 1
3 0 2
1 2 0

S a m p l e O u t p u t Sample Output

3

E x p l a i n Explain

n<=200

T r a i n Train O f Of T h o u g h t Thought

F l o y e d Floyed 求出最短路,求最小和就OK了

C o d e Code

#include<iostream>
#include<cstdio>
using namespace std;
int INF=1e9;
int ans=1e9,n,a[505][505];
int main()
{
	scanf("%d",&n);
	for (int i=1; i<=n;++i)
	 for (int j=1; j<=n; ++j) { 
	 	scanf("%d",&a[i][j]);
	 	if (a[i][j]==0 && i!=j) a[i][j]=INF;
	 } 
	for (int k=1; k<=n; ++k)
	 for (int i=1; i<=n; ++i)
	  for (int j=1; j<=n; ++j)
	    a[i][j]=min(a[i][j],a[i][k]+a[k][j]);//Floyed算法
	for (int i=1; i<=n; ++i)
	 {
	 	int m=0;
	 	for (int j=1; j<=n; ++j)
		 m+=a[i][j];
		ans=min(ans,m);  //求最小和
	 }
	printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/88752089
SSL