lightoj1094——Farthest Nodes in a Tree(dfs+最长路径)

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
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

给出一棵带权的树,求树上权值最高的一条路径
之前做过一道类似的题,总之是先随便以一个点dfs一次,能够到达的最远的点就是最长路径的端点,再以这个端点dfs一遍权值最大的路径就是整棵树最大的路径

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h>
#include <algorithm>
#include <queue>
#include <iomanip>
#define INF 0x3f3f3f3f
#define MAXN 30005
#define Mod 99999999
using namespace std;
struct Node
{
    int to,w;
};
int n,ans,pos;
vector<Node> mp[MAXN];
int vis[MAXN];
void dfs(int p,int dis)
{
    for(int i=0; i<mp[p].size(); ++i)
    {
        Node t=mp[p][i];
        if(!vis[t.to])
        {
            vis[t.to]=1;
            if(dis+t.w>ans)
            {
                pos=t.to;
                ans=dis+t.w;
            }
            dfs(t.to,dis+t.w);
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    for(int cas=1; cas<=t; ++cas)
    {
        memset(vis,0,sizeof(vis));
        memset(mp,0,sizeof(mp));
        scanf("%d",&n);
        for(int i=1; i<n; ++i)
        {
            int u,v,ww;
            scanf("%d%d%d",&u,&v,&ww);
            Node t;
            t.to=v;
            t.w=ww;
            mp[u].push_back(t);
            t.to=u;
            t.w=ww;
            mp[v].push_back(t);
        }
        ans=-1;
        vis[0]=1;
        dfs(0,0);
        ans=-1;
        memset(vis,0,sizeof(vis));
        vis[pos]=1;
        dfs(pos,0);
        printf("Case %d: %d\n",cas,ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值