1094-farthest Nodes in a Tree
|
PDF (中文版) |
Statistics |
Forum |
Time Limit: 2 second (s) |
Memory Limit: 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 is weighted and undirected. That's means you had to find nodes in the whose distance was maximum amongst all nodes.
Input
Input starts with an integer T (≤10), denoting the number of test cases.
Each case starts with a integer n (2≤n≤30000) denoting the total number of nodes in the tree. The nodes is numbered from 0 to n-1. Each of the next n-1lines would contain three integers u v w (0≤u, v < N, U≠v, 1≤w≤10000) Deno Ting that node u and v are connected by a edge whose weight is w. You can assume that the input would form a valid tree.
Output
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 |
Notes
The Dataset is huge, and the use faster I/O methods.
Test instructions: Find the diameter of the tree, water problem ...
AC Code:
#include <cstdio> #include <cstring> #include <queue> #include <stack> #include <vector># Include <cmath> #include <cstdlib> #include <algorithm> #define MAXN 30000+10#define MAXM 60000+10# Define INF 1000000#define EPs 1e-8using namespace std;struct edge{int from, to, Val, next;}; Edge Edge[maxm];int HEAD[MAXN], Edgenum;int dist[maxn];bool vis[maxn];int node, ans;int n;int k = 1;void init () {Edgenu m = 0; Memset (Head,-1, sizeof (head));} void Addedge (int u, int v, int w) {Edge E = {u, V, W, Head[u]}; Edge[edgenum] = E; Head[u] = edgenum++;} void Getmap () {int A, b, C; for (int i = 1; i < N; i++) {scanf ("%d%d%d", &a, &b, &c); a++, b++; Addedge (A, B, c); Addedge (b, A, c); }}void BFS (int sx) {queue<int> Q; memset (Dist, 0, sizeof (Dist)); Memset (Vis, false, sizeof (VIS)); VIS[SX] = true; Ans = 0; node = SX; Q.push (SX); while (! Q.empty ()) {int U = Q.front (); Q.pop (); for (int i = head[u]; i =-1; i = Edge[i].next) {Edge E = Edge[i]; if (!vis[e.to] && dist[e.to] < Dist[u] + e.val) {vis[e.to] = true; Dist[e.to] = Dist[u] + e.val; if (Dist[e.to] > ans) {ans = dist[e.to]; node = e.to; } q.push (e.to); }}}}void Solve () {BFS (1); BFS (node); printf ("Case%d:", k++); printf ("%d\n", ans);} int main () {int t; scanf ("%d", &t); while (t--) {scanf ("%d", &n); Init (); Getmap (); Solve (); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lightoj 1094-farthest Nodes in a tree "diameter nude"