题目链接:http://acm.hrbeu.edu.cn/index.php?act=problem&id=1209
Go To Play
TimeLimit: 1 Second MemoryLimit: 32 Megabyte
Totalsubmit: 343 Accepted: 131
Description
There are N(N<=50) good friends. One day they want to play together in one of their home. There may be road between two houses. We can describe a house as an vertex and a road as a edge between two vertexes. Every one goes at the same speed. At the very beginning, everyone stays at their own home. Now they want to play together as early as possible, that's to say they expect the latest one reach destination as early as possible. But they don't know whose house to get together in, can you help them?
Input
Input contains multiple cases. The first line is a integer T representing the number of test cases.The first line of each case contains two integers N and M. Then M lines follow. Each of the M lines contains three integers a, b, and c,which means that vertex a and b exist a edge whose distance is c.
Output
For each test case find which vertex to get together. If there is no such vertex print a single line "No solution." instead.
Sample Input
3
3 2
0 1 10
1 2 10
4 3
0 1 10
1 2 10
2 3 10
4 2
0 1 5
2 3 7
Sample Output
1
1
No solution.
首先判断连通性,如果不连通输出“No solution.”,注意后面还有个“.”,坑在这好长时间。
之后用floyd求一遍最短路,最后再扫一遍就行了。
/*************************************************************************
> File Name: HEU/1209.cpp
> Author: magicyang
> Mail:273868471@qq.com
> Created Time: 2014年08月30日 星期六 13时24分41秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int parent[55];
int dist[55][55];
const int maxn=1000000000;
int Find(int x)
{
if(parent[x]==x) return x;
else return parent[x]=Find(parent[x]);
}
void start(int n)
{
for(int i=0;i<=n;i++)
parent[i]=i;
}
void floyd(int n)
{
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(dist[i][j]>dist[i][k]+dist[k][j])
dist[i][j]=dist[i][k]+dist[k][j];
}
}
}
}
int check(int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i) sum++;
}
if(sum>1) return 1;
else return 0;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
start(n);
for(int i=0;i<=n;i++)
{
for(int j=0;j<=n;j++)
{
if(i==j) dist[i][j]=0;
else dist[i][j]=maxn;
}
}
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
int xx=Find(x),yy=Find(y);
if(xx!=yy) parent[xx]=yy;
if(dist[x][y]>z)
{
dist[x][y]=z;
dist[y][x]=z;
}
}
if(check(n)) cout<<"No solution."<<endl;
else
{
floyd(n);
/*for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<dist[i][j]<<" ";
cout<<endl;
}*/
int ans=0;
int minn=maxn;
for(int i=0;i<n;i++)
{
int maxx=0;
for(int j=0;j<n;j++)
{
if(dist[i][j]>maxx) maxx=dist[i][j];
}
if(maxx<minn)
{
minn=maxx;
ans=i;
}
}
cout<<ans<<endl;
}
}
}