I. 蚂蚁上树

蚂蚁上树(Sauteed Vermicelli with minced Pork),又名肉末粉条,是四川省及重庆市的特色传统名菜之一。因肉末贴在粉丝上,形似蚂蚁爬在树枝上而得名。这道菜具体的历史,已不可考。但在四川省、重庆市一带,该菜很常见。

蚂蚁上树通常由粉丝(或者粉条)、肉末为主料,辅以胡萝卜、姜、葱、豆瓣酱等辅料制作而成。成菜后,口味清淡,爽滑美味,色泽红亮,食之别有风味。

蚂蚁想知道这棵树上距离最远的两个点之间的距离

给你一个具有 n 个节点的树

求这棵树上距离最远的两个点之间的距离

输入格式

第一行一个整数 n ,(1n104)

接下来 n1 行,每行三个整数 x,y,z 表示 x 与 y 之间有一条长度为 z 的边 (1x,yn,1z104)

输出格式

一个整数表示树上距离最远的两个点之间的距离

样例

input
5
1 2 9
1 3 3
1 5 2
2 4 10
output
22

简单的树的直径。。。就是有点忘了。。。。。

 
 
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int N=1E4+9;
struct stu{
    int a,b;
};
vector <stu>ve[N];
int mark[N];
int point ;
int step[N];
int ans=0;
void bfs(int x){
    queue<int >que;
    que.push(x);
    mark[x]=1;
    step[x]=0;
    while(que.size()){
        int y=que.front();
        que.pop();
        if(ans<step[y]){
            ans=step[y];
            point=y;
        }
        for(int i=0;i<ve[y].size();i++){
            if(mark[ve[y][i].a]!=1){
                mark[ve[y][i].a]=1;
                step[ve[y][i].a]=step[y]+ve[y][i].b;
                que.push(ve[y][i].a);
            }
        }
    }
}
int main(){
    
    int n;
    cin>>n;
    int x,y,z;
    for(int i=0;i<n-1;i++){
        cin>>x>>y>>z;
        ve[x].push_back({y,z});
        ve[y].push_back({x,z});
    }
    memset(mark,0,sizeof(mark));
     ans=0;
     bfs(1);
     memset(mark,0,sizeof(mark));
     ans=0;
     bfs(point);
     cout<<ans<<endl;
    
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/Accepting/p/11297281.html
今日推荐