[JLOI2009]二叉树问题

题目链接 https://www.luogu.org/problemnew/show/P3884

跑一遍dfs ,标记每一个点的深度,统计最大深度;利用桶统计宽度;
跑一边lca,求公共祖先
#include <iostream>
#include <fstream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
int qread() {
    int x=0;
    char ch=getchar();
    while (ch>'9'||ch<'0')ch=getchar();
    while (ch>='0'&&ch<='9') {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x;
}
short int n,en=0,x,y;
const int maxn =101;
struct edge {
    short int fr,gt,nxt;
};
short int dep[maxn],d_num[maxn],head[maxn],st,ed,lg[maxn],ans_w=0,ans_d=0,f[maxn][8];
edge e [maxn*2];
void adg(int x,int y) {
    ++en;
    e[en].fr=x;
    e[en].gt=y;
    e[en].nxt=head[x];
    head[x]=en;
}
void dfs(int x,int fa) {
    dep[x]=dep[fa]+1;
    ans_d=max(ans_d,dep[x]);
    ++d_num[dep[x]];
    ans_w=max(ans_w,d_num[dep[x]]);
    f[x][0]=fa;
    //cout<<x<<' '<<dep[x]<<endl;
    for (int i=1; i<=100; i++) {    //wa1
        f[x][i]=f[f[x][i-1]][i-1];
        if(!f[x][i])break;
    }
    for (int i=head[x]; i; i=e[i].nxt) {
        if(e[i].gt==fa)continue;
        dfs(e[i].gt,x);
    }
}
int LCA(int x,int y) {
    //cout<<x<<' '<<y<<endl;
    if(dep[x]<dep[y]) {
        int t=x;
        x=y;
        y=t;
    }
    while (dep[x]>dep[y])x=f[x][lg[dep[x]-dep[y]]];
    if(x==y)return x;
    //cout<<f[x][0]<<' '<<f[y][0]<<endl;
    int fr=lg[dep[x]];
//  cout<<dep[x]<<' '<<fr<<endl;
    for (int i=fr; i>=0; i--) { //wa2
        if(f[x][i]!=f[y][i]) {
            x=f[x][i];
            y=f[y][i];

        }
    }
    return f[x][0];
}
int main() {
//  freopen ("3884.in","r",stdin);
    memset (head,0,sizeof(head));
    memset (d_num,0,sizeof(d_num));
    n=qread();
    for (int i=1; i<n; i++) {
        x=qread();
        y=qread();
        adg(x,y);
        adg(y,x);
    }
    for (int i=1; i<=n; i++) {
        lg[i]=lg[i-1];
        if(1<<lg[i]==i)++lg[i];
    }
    for (int i=0; i<=n; i++)--lg[i];
    st=qread();
    ed=qread();
    dep[0]=0;
    dfs(1,0);
    int rt = LCA (st,ed);
    cout<<ans_d<<endl;
    cout<<ans_w<<endl;
    cout<<(dep[st]-dep[rt])*2+dep[ed]-dep[rt]<<endl;
    fclose (stdin);
    fclose (stdout);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值