树形dp?
可以吧
但我求树上最长链
以链的一端为root建树
每一个点到达的最长距离
就是这个点到达最长链的距离(可以倍增预处理)
加上到达的点向上向下的最大值(最长链预处理)
#include <cstring>
#include <cstdio>
#include <queue>
#define cle(a,b) memset(a,b,sizeof a)
#define lp(i,j,k) for(int i = j;i <= k;++i)
using namespace std;
int read () {
char c = getchar();
int re = 0;
for(;c > '9' || c < '0';c = getchar());
for(;c <= '9' && c >= '0';c = getchar())
re = re * 10 + c - '0';
return re;
}
int n,U,V,MAXDIS;
int fa[10010][16];
int path[10010][16];
int depth[10010];
struct edge {
int u,v,w,next;
}e[20020];
int cnt,head[10010];
typedef pair<int,int> pii;
queue<pii>q;
int Hash[10010];
int last[10010];
int dis[10010];
void adde (int u,int v,int w) {
e[++cnt].v = v;
e[cnt].u = u;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
e[++cnt].v = u;
e[cnt].u = v;
e[cnt].w = w;
e[cnt].next = head[v];
head[v] = cnt;
}
int bfs (int u,int ti) {
q.push(make_pair(u,0));
Hash[u] = ti;
int re = 0,rep = 1;
while(!q.empty()) {
u = q.front().first;
for(int i = head[u];i != -1;i = e[i].next) {
int v = e[i].v;
if(Hash[v] != ti) {
Hash[v] = ti;
if(ti == 2)
last[v] = i;
if(q.front().second + e[i].w > re) {
re = q.front().second + e[i].w;
rep = v;
}
q.push(make_pair(v,q.front().second + e[i].w));
}
}
q.pop();
}
if(ti == 2) {
int t = last[rep];
last[rep] = 0;
int DIS = MAXDIS = re;
while(t) {
dis[e[t].v] = re - DIS;
DIS -= e[t].w;
if(!last[e[t].u])
dis[e[t].u] = re;
int shit = last[e[t].u];
last[e[t].u] = 0;
t = shit;
}
depth[rep] = 1;
}
return rep;
}
void dfs (int u) {
for(int i = head[u];i != -1;i = e[i].next) {
int v = e[i].v;
if(!depth[v]) {
depth[v] = depth[u] + 1;
fa[v][0] = u;
path[v][0] = e[i].w;
int t = 0;
while(++t <= 15) {
if(depth[v] - (1 << t) <= 0)
break;
fa[v][t] = fa[fa[v][t - 1]][t - 1];
path[v][t] = path[v][t - 1] + path[fa[v][t - 1]][t - 1];
}
dfs(v);
}
}
}
int go_up (int u) {
int re = 0;
int t =16;
if(dis[u] == -1) {
while(--t > -1) {
if(dis[fa[u][t]] == -1) {
re += path[u][t];
u = fa[u][t];
}
}
re += path[u][0];
u = fa[u][0];
}
if(dis[u] > MAXDIS - dis[u])
re += dis[u];
else re += MAXDIS - dis[u];
return re;
}
int main () {
while(scanf("%d",&n) != EOF) {
cle(last,0);
cnt = 0;
cle(fa,0);
cle(path,0);
cle(Hash,0);
cle(head,-1);
cle(dis,-1);
cle(depth,0);
lp(i,2,n) {
U = read();
V = read();
adde(i,U,V);
}
dfs(bfs(bfs(1,1),2));
dis[0] = 0;
lp(i,1,n)
printf("%d\n",go_up(i));
}
}