【题意】:
题目大概意思是给你一棵树,让你找树上最长距离的路径。两次 bfs ,就可以得到树的直径了。
The longest distance between two nodes in a tree is called the diameter of the tree. Tree is a connected graph with no cycles. The steps to find the diameter of a tree are:
- Select any node a and find the node x farthest from it.
- Again find the node y farthest from x. The distance between x and y is called the diameter of the tree.
For the following given scenarios, find the diameter of the trees.
Input Specification
There are T (≤ 10) test cases.
For each case, you will be given one integer n (2 ≤ n ≤ 30000) denoting the number of nodes in the tree. The nodes are 0-indexed (that means, they are numbered from 0 to n-1). The next n-1 lines will contain three integers p q r (0 ≤ p, q < n, p ≠ q, 1 ≤ r ≤ 10000) denoting that node p and q are connected by an edge whose weight is r.
Output Specification
Print the case number and the diameter.
Sample Input
2
4
0 1 20
1 2 30
2 3 50
5
0 2 20
2 1 10
0 3 29
0 4 50
Sample Output
Case 1: 100
Case 2: 80
ac代码:
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn=3e4+10;
int dis[maxn],ans;
bool vis[maxn];
vector<pair<int ,int > >c[maxn];
int bfs(int x)
{
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
queue<int >qe;
qe.push(x);
vis[x]=1;
int p=0;
while(!qe.empty()){
int f=qe.front();
qe.pop() ;
if(dis[f]>ans){
ans=dis[f];
p=f;
}
pair<int ,int >t;
for(int i=0;i<c[f].size();i++){
t=c[f][i];
if(vis[t.first]==0)
{
vis[t.first]=1;
dis[t.first]=dis[f]+t.second;
qe.push(t.first);
}
}
}
return p;
}
int main()
{
int t,n,x,y,z,m=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n-1;i++){
scanf("%d%d%d",&x,&y,&z);
c[x].push_back(make_pair(y,z));
c[y].push_back(make_pair(x,z));
}
ans=0;
int k=bfs(0);
// printf("%d\n",k);
ans=0;
bfs(k);
printf("Case %d: %d\n",++m,ans);
for(int i=0;i<=n;i++)
c[i].clear();
}
return 0;
}
370




被折叠的 条评论
为什么被折叠?



