题意:给你一个二叉树,输出它的深度,宽度,以及对于结点u和v输出它们的距离
u和v的距离定义:设u和v的最近公共祖先为c,dist(u, v) = dist(u, c) * 2 + dist(v, c);
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 110;
int n;
int cnt[N], st[N];
int h[N], e[N], ne[N], idx;
int p[N]; // 结点的双亲结点
int w, d; // 宽度,深度
void add(int a, int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int dfs(int u, int l){
st[u] = 1;
cnt[l] ++;
w = max(cnt[l], w);
d = max(l, d);
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(st[j] == 0) dfs(j, l + 1);
}
}
int lca(int u, int v, int step1, int step2){
if(u == v) return step1 * 2 + step2;
if(u < v) return lca(u, p[v], step1, step2 + 1); // 根据序号大小来爬树
return lca(p[u], v, step1 + 1, step2);
}
int main(){
memset(h, -1, sizeof h);
cin >> n;
for(int i = 0; i < n - 1; i ++){
int a, b;
cin >> a >> b;
add(a, b);
p[b] = a;
}
dfs(1, 1);
cout << d << endl << w << endl;
int u, v;
cin >> u >> v;
cout << lca(u, v, 0, 0);
return 0;
}