【树的直径】Farthest Nodes in a Tree

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

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-1 lines 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.

Output

For each case, print the case number and the maximum distance.

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<stdio.h>
#include<string.h>
#include<queue>
#include <iostream>
#define MAX 100000
using namespace std;
int head[MAX];
int vis[MAX];
int dis[MAX];
int n, m, ans;
int sum;
int aga;
struct node
{
  int u, v, w;
  int next;
}edge[MAX];
void add(int u, int v, int w)
{
  edge[ans].u = u;
  edge[ans].v = v;
  edge[ans].w = w;
  edge[ans].next = head[u];
  head[u] = ans++;
}
void getmap()
{
  int i, j;
  int a, b, c;
  ans = 0;
  memset(head, -1, sizeof(head));
  while (m--)
  {
    scanf("%d%d%d", &a, &b, &c);
    add(a, b, c);
    add(b, a, c);
  }
}
void bfs(int beg)
{
  queue<int>q;
  memset(dis, 0, sizeof(dis));
  memset(vis, 0, sizeof(vis));
  int i, j;
  while (!q.empty())
    q.pop();
  aga = beg;
  sum = 0;
  vis[beg] = 1;
  q.push(beg);
  int top;
  while (!q.empty())
  {
    top = q.front();
    q.pop();
    for (i = head[top]; i != -1; i = edge[i].next)
    {
      if (!vis[edge[i].v])
      {
        dis[edge[i].v] = dis[top] + edge[i].w;
        vis[edge[i].v] = 1;
        q.push(edge[i].v);
        if (sum < dis[edge[i].v])
        {
          sum = dis[edge[i].v];
          aga = edge[i].v;
        }
      }
    }
  }
}
int main()
{
  int T = 0;
  cin >> T;
  int cas = 0;
  while (T--)
  {
    cin >> n;
    m = n - 1;
    getmap();
    bfs(1);//搜索最长路径的一个端点
    bfs(aga);//搜索另一个端点
    printf("Case %d: %d\n", ++cas,sum);
  }
  return 0;
}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

14 − 7 =