Test instructions: Each operation new plus two leaf nodes, each time after the operation to ask the diameter of the tree.
Maintain the two endpoints of the tree's diameter u,v, each time calculating the distance from the newly added leaf node to the u,v two point, if there is a longer update.
Because the diameter of the tree according to the method, if the new diameter, must be to u or to V distance farthest.
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 6 Const intMAXN =1000000+ +;7 Const intLOGMAXN = -;8 9 intN, Q;Ten One intL[MAXN]; A intFA[MAXN]; - intANC[MAXN][LOGMAXN]; - the voidAddintUintPA) - { -Fa[u] =PA; -L[u] = L[pa] +1; +anc[u][0] =PA; - for(intj =1; (1<< j) < n; J + +)if(anc[u][j-1]) +ANC[U][J] = anc[anc[u][j-1]][j-1]; A } at - intLCA (intPintq) - { - if(L[p] <L[q]) Std::swap (p, q); - intlog; - for(log =1; (1<< log) <= l[p]; log++); log--; in for(inti = log; I >=0; i--) - if(L[p]-(1<< i) >= l[q]) p =Anc[p][i]; to if(p = = q)returnp; + for(inti = log; I >=0; i--) - if(Anc[p][i] && anc[p][i]! =Anc[q][i]) thep = anc[p][i], q =Anc[q][i]; * returnFa[p]; $ }Panax Notoginseng - intDistanceintUintv) the { + intL =LCA (U, v); A returnL[u] + l[v]-l[l] *2; the } + - intMain () $ { $scanf"%d", &Q); -n =4; -fa[2] = fa[3] = fa[4] =1; thel[2] = l[3] = l[4] =1; -anc[2][0] = anc[3][0] = anc[4][0] =1;Wuyi the intU =2, V =3, diameter =2; - while(q--) Wu { - intP scanf"%d", &p); AboutAdd (+ +n, p); $Add (+ +n, p); - intL1 = Distance (n, U), L2 =distance (n, V); - if(L1 >= L2 && L1 >=diameter) - { AV =N; +diameter =L1; the } - Else if(L2 >= L1 && L2 >=diameter) $ { theU =N; thediameter =L2; the } theprintf"%d\n", diameter); - } in the return 0; the}code June
Codeforces 379F tree diameter New year tree