#include <cstdio> #include <vector> #include <algorithm> #include <memory> using namespace std;
const int maxN = 10005;
struct edge { int v; long long w; edge() { v = 0; w = 0; } edge(int _v, long long _w) :v(_v), w(_w) { } };
vector<edge> edges[maxN]; bool visit[maxN]; long long path[maxN]; int source;
void dfs(int s, long long length) { visit[s] = true; for (int i = 0; i < edges[s].size(); i++) { int temp = edges[s].at(i).v; long long tempW = edges[s].at(i).w; if (!visit[temp]) { path[temp] = max(path[temp], length + tempW); if (path[source] < path[temp]) source = temp; dfs(temp, length + tempW); } } }
void thePath(int n) { source = 1; memset(visit, false, sizeof(visit)); memset(path, 0, sizeof(path));
dfs(1, 0);
memset(visit, false, sizeof(visit)); dfs(source, 0);
memset(visit, false, sizeof(visit)); dfs(source, 0); for (int i = 1; i <= n; i++) printf("%lld\n", path[i]); }
int main() { int n; while (scanf_s("%d", &n) != EOF) { for (int i = 2; i <= n; i++) { int a; long long b; scanf_s("%d %lld", &a, &b); edge e1(a, b); edge e2(i, b); edges[i].push_back(e1); edges[a].push_back(e2); } thePath(n); for (int i = 0; i <= n; i++) edges[i].clear(); }
return 0; }
|