点击打开题目
1094 - Farthest Nodes in a Tree
PDF (English) | Statistics | Forum |
|---|
Time Limit: 2 second(s) | Memory Limit: 32 MB |
|---|
Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the tree whose distance is maximum amongst all nodes.
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with an integer n (2 ≤ n ≤ 30000) denoting the total number of nodes in the tree. The nodes are numbered from 0 to n-1. Each of the next n-1lines will contain three integers u v w (0 ≤ u, v < n, u ≠ v, 1 ≤ w ≤ 10000) denoting that node u and v are connected by an edge whose weight is w. You can assume that the input will form a valid tree.
For each case, print the case number and the maximum distance.
Sample Input | Output for 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 | Case 1: 100 Case 2: 80 |
Dataset is huge, use faster i/o methods.
树的直径的裸题,两次dfs即可。
代码如下:
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MAX 40000
int n;
vector<int> mapp[MAX+5];
vector<int> dis[MAX+5];
int f[MAX+5]; //距离当前点的距离
bool vis[MAX+5];
void init()
{
for (int i = 0 ; i < n ; i++)
{
mapp[i].clear();
dis[i].clear();
}
}
int dfs(int x)
{
int ans; //最远点
int maxx = 0; //最大距离
queue<int> q; //存放根
CLR(vis,false);
CLR(f,0);
f[x] = 0;
q.push(x);
while (!q.empty())
{
int st = q.front();
q.pop();
vis[st] = true;
for (int i = 0 ; i < mapp[st].size() ; i++)
{
if (!vis[mapp[st][i]]) //该点没有用过
{
q.push(mapp[st][i]);
f[mapp[st][i]] = f[st] + dis[st][i];
if (f[mapp[st][i]] > maxx)
{
maxx = f[mapp[st][i]];
ans = mapp[st][i]; //记录节点
}
}
}
}
return ans;
}
int main()
{
int u;
int Case = 1;
scanf ("%d",&u);
while (u--)
{
scanf ("%d",&n);
init();
for (int i = 1 ; i < n ; i++)
{
int t1,t2,t3;
scanf ("%d %d %d",&t1,&t2,&t3);
mapp[t1].push_back(t2);
dis[t1].push_back(t3);
mapp[t2].push_back(t1); //求树的直径一定要双向存图
dis[t2].push_back(t3);
}
int st = dfs(0); //任意从一点开始bfs
int ans = dfs(st);
printf ("Case %d: %d\n",Case++,f[ans]);
}
return 0;
}