链接:https://www.nowcoder.com/acm/contest/157/D
来源:牛客网
插排树
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
一年一度的山东省oi夏令营又开始了,每到这个季节,山东的oier们都会欢聚这里,一起学(tuí)习(feì)。当然,为了能更加愉快地学(tuí)习(feì),就少不了要自带电脑,用电便开始成了一种问题,于是便有一种神奇的数据结构诞生了!这就是山东省oi专用数据结构——插排树(如图)
小K为了能更好的学(tuí)习(feì),所以他想尽量的往后做,所以现在请你帮帮他,他最远可以离讲台多远。
已知插排树的根节点在讲台上,有且仅有一个根节点(根节点入度为0),最远距离即所有插排的长度,小K电脑线的长度忽略不计
本题良心大样例下载地址: https://kench.co/tree.zip
输入描述:
第一行一个整数n表示有n个节点
然后n-1行,每行三个整数a,b,c,表示插排a是接在插排b上的,插排a的长度为c
输出描述:
一个整数n表示最远距离
示例1
输入
复制
9
2 1 2
3 1 2
4 1 1
5 2 3
6 2 1
7 3 1
8 3 4
9 7 5
输出
复制
8
说明
1=>3=>7=>9
备注:
对于30%的数据 n<233
对于70%的数据 n<2333
对于100%的数据 n<50000
c小于20
a,b小于等于n
最长路代码如下
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cctype>
#include <set>
#define maxn 500005
typedef long long ll;
using namespace std;
ll n,m,k,cnt;
ll head[maxn];
ll rec[maxn],ma;
ll flag[maxn] = {0};
struct edge
{
ll b,c,next;
}
plan[maxn];
struct node
{
ll edg;
ll dis;
node(ll xx,ll yy):edg(xx),dis(yy){}
bool operator < (const node nod) const
{
return dis < nod.dis;
}
};
void bulid(ll b,ll a,ll c)
{
plan[++cnt].next = head[a];
plan[cnt].b = b;
plan[cnt].c = c;
head[a] = cnt;
}
void bfs(ll be)
{
priority_queue<node>q;
q.push(node(be,0));
while(!q.empty())
{
node mr = q.top();
q.pop();
flag[mr.edg] = 1;
rec[mr.edg] = max(rec[mr.edg],mr.dis);
ma = max(rec[mr.edg],ma);
if (mr.dis != rec[mr.edg]) continue;
for(int i = head[mr.edg]; i != 0; i = plan[i].next)
{
ll ww = plan[i].b;
if(flag[ww] == 0 && mr.dis+plan[i].c > rec[ww])
{
rec[ww] = mr.dis + plan[i].c;
q.push(node(ww,mr.dis+plan[i].c));
}
}
}
}
set<int> kb;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 1;i <= n; i ++)
{
kb.insert(i);
}
for(int i = 1; i <= n-1; i ++)
{
ll x,y,z;
cin >> x >> y >> z;
bulid(x,y,z);
kb.erase(x);
}
bfs(*kb.begin());
cout << ma << endl;
return 0;
}