题意:
初始时,给你:
每次给你一个点,让你增加这个节点的2个儿子,每次输出直径的长度。
题解:
先找到初始时的直径(2->3 len:2) 或 (2->4 len:2)或 (3->4 len:2)。每次加点时,动态维护直径的两个端点和长度,即每次计算新点与原直径的两个端点的距离,若大于原直径,则更新。怎么求?新加点时,设该点为u,则设dp[0][u] 为它的父亲结点。用倍增求LCA,即可。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int N = 1000006;
//int head[N], nxt[N * 2], pnt[N * 2], E;
int dp[21][N], dist[N];
/*void init(){
E = 0;
memset(head, -1, sizeof(head));
}
void add_edge(int a, int b){
pnt[E] = b;
nxt[E] = head[a];
head[a] = E++;
}*/
int lca(int a,int b){
if(dist[a] > dist[b]) swap(a, b);
int g = dist[b] - dist[a], i;
for(i = 0; i <= 20; i++){
if(g & (1 << i)){
b = dp[i][b];
}
}
if(a == b) return a;
for(i = 20; i >= 0; i--){
if(dp[i][a] == dp[i][b])continue;
a = dp[i][a];
b = dp[i][b];
}
return dp[0][a];
}
int main(){
int n = 4;//结点数
dist[1] = 0; //初始状态
//add_edge(1, 2);
//add_edge(2, 1);
dp[0][2] = 1;
dist[2] = 1;
//add_edge(1, 3);
//add_edge(3, 1);
dp[0][3] = 1;
dist[3] = 1;
//add_edge(1, 4);
//add_edge(4, 1);
dp[0][4] = 1;
dist[4] = 1;
int s = 2;
int t = 3;
int len = 2;
int q, nnode, lcas, lcat;
int dists, distt;
int i, j;
scanf("%d", &q);
for(i = 1; i <= q; i++){
scanf("%d", &nnode);
//加第一个儿子
n++;
//add_edge(n, nnode);
//add_edge(nnode, n);
dp[0][n] = nnode;
dist[n] = dist[nnode] + 1;
for(j = 1; j <= 20; j++){
dp[j][n] = dp[j - 1][dp[j - 1][n]];
}
lcas = lca(s, n);
lcat = lca(t, n);
dists = dist[s] + dist[n] - 2 * dist[lcas];
distt = dist[t] + dist[n] - 2 * dist[lcat];
if(dists > len){
//s = s;
t = n;
len = dists;
}
if(distt > len){
s = n;
//t = t;
len = distt;
}
//加第二个儿子
n++;
//add_edge(n, nnode);
//add_edge(nnode, n);
dp[0][n] = nnode;
dist[n] = dist[nnode] + 1;
for(j = 1; j <= 20; j++){
dp[j][n] = dp[j - 1][dp[j - 1][n]];
}
lcas = lca(s, n);
lcat = lca(t, n);
dists = dist[s] + dist[n] - 2 * dist[lcas];
distt = dist[t] + dist[n] - 2 * dist[lcat];
if(dists > len){
//s = s;
t = n;
len = dists;
}
if(distt > len){
s = n;
//t = t;
len = distt;
}
printf("%d\n", len);
}
return 0;
}