TOJ 3517 The longest athletic track(树直径)

After a long time of algorithm training, we want to hold a running contest in our beautiful campus. Because all of us are curious about a coders's fierce athletic contest,so we would like a more longer athletic track so that our contest can last more .


In this problem, you can think our campus consists of some vertexes connected by roads which are undirected and make no circles, all pairs of the vertexes in our campus are connected by roads directly or indirectly, so it seems like a tree, ha ha.


We need you write a program to find out the longest athletic track in our campus. our athletic track may consist of several roads but it can't use one road more than once.

Input

*Line 1: A single integer: T represent the case number T <= 10
For each case
*Line1: N the number of vertexes in our campus 10 <= N <= 2000
*Line2~N three integers a, b, c represent there is a road between vertex a and vertex b with c meters long
1<= a,b <= N,  1<= c <= 1000;

Output

For each case only one integer represent the longest athletic track's length

Sample Input

1
7
1 2 20
2 3 10
2 4 20
4 5 10
5 6 10
4 7 40

Sample Output

80

 题目给出了一棵生成树,问这棵生成树最长的路的长度是多少。

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <queue>
using namespace std;
const int MaxSize=100001;
int map[2002][2002];
int sum[2002];
bool visit[2002];
int n;
int Max;
int bfs(int v)
{
    for (int i=1; i<=n; i++)
    {
        visit[i]=false;
        sum[i]=0;
    }
    Max=0;
    queue<int> q;
    q.push(v);
    int k,key=0;
    while (!q.empty())
    {
        k=q.front();
        q.pop();
        for (int i=1; i<=n; i++)
        {
            if(map[k][i]!=MaxSize && !visit[i])
            {
                visit[i]=true;
                q.push(i);
                sum[i]=sum[k]+map[k][i];
                if(sum[i]>Max)
                {
                    Max=sum[i];
                    key=i;
                }
            }
        }
    }
    return key;
}
int main()
{
    int ans;
    cin>>ans;
    while (ans--)
    {
        cin>>n;
        for (int i=1; i<=n; i++)
        {
            for (int j=1; j<=n; j++)
            {
                map[i][j]=MaxSize;
            }
        }
        for (int i=1; i<n; i++)
        {
            int a,b,w;
            cin>>a>>b>>w;
            map[a][b]=map[b][a]=w;
        }
        int key;
        key=bfs(1);
        key=bfs(key);
        cout<<Max<<endl;
    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值