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

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

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

I n p u t Input Input

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

O u t p u t Output Output

最短路径之和;

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

3
0 3 1
3 0 2
1 2 0

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

3

E x p l a i n Explain Explain

n<=200

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

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

C o d e Code Code

#include
#include
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;
}

你可能感兴趣的:(最短路,Floyed)