codeforces 379F New Year Tree

题意:

初始时,给你:
在这里插入图片描述
每次给你一个点,让你增加这个节点的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值