-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path149.cpp
More file actions
85 lines (73 loc) · 1.57 KB
/
149.cpp
File metadata and controls
85 lines (73 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 10011;
vector<pair<int, int> >a[N];
int disx[N], disy[N], dis[N], n;
bool st[N];
int x, y, mx, my;
int main () {
int i, j, k;
queue<int> q;
//freopen ("in", "r", stdin);
scanf ("%d", &n);
for (i = 2; i <= n; ++i) {
scanf ("%d%d", &j, &k);
a[i].push_back ({j, k});
a[j].push_back ({i, k});
}
fill (dis, dis + n + 1, -1);
fill (disx, disx + n + 1, -1);
fill (disy, disy + n + 1, -1);
mx = my = -1; x = y = 1;
q.push (1); dis[1] = 0;
while (!q.empty ()) {
int u = q.front (); q.pop ();
k = a[u].size ();
for (j = 0; j < k; ++j) {
int v = a[u][j].first, w = a[u][j].second;
if (dis[v]==-1) {
dis[v] = dis[u] + w;
if (dis[v] > mx) {
mx = dis[v];
x = v;
}
q.push (v);
}
}
}
q.push (x); disx[x] = 0;
while (!q.empty ()) {
int u = q.front (); q.pop ();
k = a[u].size ();
for (j = 0; j < k; ++j) {
int v = a[u][j].first, w = a[u][j].second;
if (disx[v] == -1) {
disx[v] = disx[u] + w;
if (disx[v] > my) {
my = disx[v];
y = v;
}
q.push (v);
}
}
}
q.push (y); disy[y] = 0;
while (!q.empty ()) {
int u = q.front (); q.pop ();
k = a[u].size ();
for (j = 0; j < k; ++j) {
int v = a[u][j].first, w = a[u][j].second;
if (disy[v] == -1) {
disy[v] = disy[u] + w;
q.push (v);
}
}
}
for (i = 1; i <= n; ++i)
printf ("%d\n", max (disx[i], disy[i]));
return 0;
}