本帖最后由 xiaosi4081 于 2022-11-6 16:50 编辑 #include<bits/stdc++.h>
using namespace std;
struct tree{
int num;
int c;
int lc,rc,fa;
}trees[105];
int sum[105];
int resa=0,resb=0;
void dfs(int num){
if(trees[num].lc==0&&trees[num].rc==0){
resa=max(resa,trees[num].c);
return ;
}
if(trees[num].lc)dfs(trees[num].lc);
if(trees[num].rc)dfs(trees[num].rc);
}
bool dfs1(int num,int f){
if(num==f)return 1;
int a=0;
if(trees[num].lc)a+=dfs1(trees[num].lc,f);
if(trees[num].rc)a+=dfs1(trees[num].rc,f);
return a;
}
void dfs2(int i){
if(trees[i].fa)trees[i].c=trees[trees[i].fa].c+1;
//cout<<i<<" "<<trees[i].c<<" "<<trees[i].lc<<" "<<trees[i].rc<<endl;
if(trees[i].lc)dfs2(trees[i].lc);
if(trees[i].rc)dfs2(trees[i].rc);
}
int main(){
int n;cin >> n;
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
if(trees[u].lc){
trees[u].rc=v;
trees[v].fa=u;
}
else{
trees[u].lc=v;
trees[v].fa=u;
}
}
int treeup=1;
while(trees[treeup].fa){
treeup=trees[treeup].fa;
}
trees[treeup].c=1;
//trees[i].c=trees[trees[i].fa].c+1;
dfs2(treeup);
dfs(1);
for(int i=1;i<=n;i++){
sum[trees[i].c]++;
resb=max(resb,sum[trees[i].c]);
}
int x,y;
cin>>x>>y;
int resc=1000000000;
for(int i=1;i<=n;i++){
if(dfs1(i,x)&&dfs1(i,y)){
resc=min(resc,(trees[x].c-trees[i].c)*2+(trees[y].c-trees[i].c));
}
}
cout<<resa<<'\n'<<resb<<'\n'<<resc;
return 0;
}
不打表方法!
第1测试点,不保证父节点编号大于子节点
所以要用dfs方式赋值
有图为证:
思路:
爆搜LCA
PS:LCA, ​最近公共祖先。
加上
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
效率更快 |