[JLOI2009]二叉树问题

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

跑一遍dfs ,标记每一个点的深度,统计最大深度;利用桶统计宽度;

跑一边lca,求公共祖先

#include 
#include 
#include 
#include 
#include 
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<
    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<
    if(dep[x]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<
    int fr=lg[dep[x]];
//  cout<
    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; ifor (int i=1; i<=n; i++) {
        lg[i]=lg[i-1];
        if(1<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<cout<cout<<(dep[st]-dep[rt])*2+dep[ed]-dep[rt]<return 0;
}

你可能感兴趣的:(图论)