【GDKOI2014模拟】树的直径

题目大意:

并不想讲。

题解:

树的直径有一个性质。

现在有两棵树,如果把它们随意连一条边,会变成一棵树,新树的直径的端点一定是之前两棵树的直径的共4个端点的两个。

所以这题搞个倍增就可以在线了。

Code:

#include<cstdio> 
#include<algorithm>
#define fo(i, x, y) for(int i = x; i <= y; i ++)
#define fd(i, x, y) for(int i = x; i >= y; i --)
#define max(a, b) ((a) > (b) ? (a) : (b))
using namespace std;

const int N = 500000;

int n, a[N], tot;
int son[N][2], dep[N];
int f[17][N], ans;

int lca(int x, int y) {
    if(dep[x] < dep[y]) swap(x, y);
    fd(i, 16, 0) if(dep[f[i][x]] >= dep[y]) x = f[i][x];
    if(x == y) return x;
    fd(i, 16, 0) if(f[i][x] != f[i][y]) x = f[i][x], y = f[i][y];
    return f[0][x];
}

int dis(int x, int y) {
    int lc = lca(x, y);
    return dep[x] + dep[y] - 2 * dep[lc];
}

int main() {
    scanf("%d", &n);
    tot = 4;
    dep[1] = 1; dep[2] = dep[3] = dep[4] = 2;
    f[0][2] = f[0][3] = f[0][4] = 1;
    int p = 2, q = 4;
    fo(i, 1, n) {
        scanf("%d", &a[i]);
        son[a[i]][0] = ++ tot;
        son[a[i]][1] = ++ tot;
        dep[tot - 1] = dep[tot] = dep[a[i]] + 1;
        f[0][tot - 1] = f[0][tot] = a[i];
        fo(j, 1, 16) f[j][tot - 1] = f[j - 1][f[j - 1][tot - 1]], f[j][tot] = f[j - 1][f[j - 1][tot]];
        if(dis(p, tot) < dis(q, tot)) swap(p, q);
        if(dis(p, q) < dis(p, tot)) q = tot;
        ans = max(ans, dis(p, q));
        printf("%d\n", ans);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值