建食堂(学习用Floyd求任意两点最短距离 入门)

F - F

 CSU - 1219 

给出n个公寓的互相距离,选择在其中一个公寓楼下建食堂,要求食堂到最远的公寓的距离最短。

Input

每组数据第一行为两个正整数n,m。

n表示公寓数,m表示可彼此直达的公寓对。

接下来m行每行给出两个彼此可直达的公寓i、j和它们之间的距离k。

2 <= n <= 100,0 <= m < (n - 1) * n / 2,0 <= i,j < n,0 < k < 10000。

Output

输出一行一个整数表示建好的食堂到最远的公寓的距离。

若无法建一个能到所有公寓的食堂,输出can not。

Sample Input

3 2
0 2 0
0 1 9

5 3
3 4 8
2 4 1
0 2 0

Sample Output

9
Can not

Hint

题意很明显了

使用floyd求最短路,最短距离存在dist[N][N]中,然后求每行的最大值,再在这些最大值中求最小值。

#include<bits/stdc++.h>
using namespace std;
const int N=105,inf=0x3f3f3f3f;
int dist[N][N];
int main()
{
	int i,j,k,n,m,a,b,d,ans;
	while(~scanf("%d%d",&n,&m))
	{
		for(i=0;i<n;i++)
		for(j=i+1;j<n;j++) dist[i][j]=dist[j][i]=inf;
		for(i=0;i<m;i++)
		{
			scanf("%d%d%d",&a,&b,&d);
			dist[a][b]=dist[b][a]=d;
		}
		for(k=0;k<n;k++)
  	 	for(i=0;i<n;i++)
 	 	for(j=0;j<n;j++)
 	 	dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
      	for(i=0;i<n;i++)
        for(j=1;j<n;j++)  dist[i][0]=max(dist[i][0],dist[i][j]);
      	ans=dist[0][0];
      	for(i=1;i<n;i++)  ans=min(ans,dist[i][0]);
      	if(ans==inf) printf("Can not\n");
      	else  printf("%d\n",ans);
  	}
  	return 0;
}

下面是最初的方法,代码十分的长。

先用一个bfs求是否是联通的,不连通输出can not

然后暴力枚举每个点到图上的最长距离,十分麻烦

不过也是A 了

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n,m;
bool vis[103],flag;
int ma[103][103];
vector<int >G[103];
int ans=0x3f3f3f3f;
void bfs(int id)
{
	queue<int>que;
	que.push(id);
	vis[id]=1;
	while(!que.empty())
	{
		int u=que.front();que.pop(); 	
		int siz=G[u].size();
		for(int i=0;i<siz;i++)
		{
			int v=G[u][i];
			if(!vis[v])
			{
				que.push(v);
				vis[v]=1;
			}
		}
	}
	for(int i=0;i<n;i++)
	{
		if(!vis[i]) flag=1;
	}
}
struct node
{
	int id,num;
	node(int a,int b)
	{
		id=a;
		num=b;
	}
};
void bfs1(int id)
{
		//printf("id:%d\n",id);
	queue<node>que;
	que.push(node(id,0));
	vis[id]=1;
	int esx=0;
	while(!que.empty())
	{
		node u=que.front();que.pop();
		esx=max(esx,u.num);
		int siz=G[u.id].size();
		for(int i=0;i<siz;i++)
		{
			int v=G[u.id][i];
			if(vis[v]==1) continue;
			vis[v]=1;
			que.push(node(v,u.num+ma[u.id][v]));
		}
	}
	//	printf("%d\n",esx);
	ans=min(ans,esx);
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
		int a,b,d;
		scanf("%d%d%d",&a,&b,&d);
		ma[a][b]=d;
		ma[b][a]=d;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	bfs(0);
	if(flag) printf("Can not\n");
	else
	{
		for(int i=0;i<n;i++)
		{
			memset(vis,0,sizeof(vis));
			bfs1(i);
		}
		cout<<ans<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41286356/article/details/88190414