洛谷:P3884 [JLOI2009]二叉树问题(树,基础,普及/提高- )

题目:

在这里插入图片描述

分析:结点u到结点v间距离。数据量比较小,不需要倍增(最近公共祖先)。

代码:

#include<bits/stdc++.h>
using namespace std;
vector<vector<int> > vv;
int m;
int fa[105];
int max_depth=0;
int depth[105];
void ddepth(int x,int dep)
{
 depth[x]=dep;
 max_depth=max(max_depth,dep);
 for(int i=0;i<vv[x].size();i++) ddepth(vv[x][i],dep+1);
 } 
int main()
{
 vector<int> v;
 cin>>m;
 for(int i=0;i<=m;i++) vv.push_back(v);
 for(int i=1;i<m;i++)
 {
  int a,b;
  cin>>a>>b;
  vv[a].push_back(b);
  fa[b]=a;
 }
 ddepth(1,1);
 cout<<max_depth<<endl;
 //宽度
 queue<int> q;
 q.push(1);
 int maxx=1;
 while(!q.empty()) 
 {
  queue<int> qq;
  while(!q.empty())
  {
   int t=q.front();
   q.pop();
   for(int i=0;i<vv[t].size();i++) qq.push(vv[t][i]);
  }
  int q_size=qq.size();
  maxx=max(maxx,q_size);
  q=qq;
 }
 cout<<maxx<<endl;
 // 
 int a1,a2,a3;
 cin>>a1>>a2;
 int aa1=a1;
 int aa2=a2;
 int dis=0;
 if(depth[a1]>=depth[a2])
 {
 while(1)
 {
  if(depth[a1]==depth[a2]) break;
  a1=fa[a1]; 
  dis++;dis++;
 }
 while(1)
 {
  if(a1==a2) 
  {
   a3=a1;break;
  }
  a1=fa[a1]; 
  a2=fa[a2];
  dis++;
  dis++;
  dis++;
 }
 cout<<dis;
 }
 else{
 while(1)
 {
  if(depth[a1]==depth[a2]) break;
  a2=fa[a2]; 
  dis++;
 }
 while(1)
 {
  if(a1==a2) 
  {
   a3=a1;break;
  }
  a1=fa[a1]; 
  a2=fa[a2];
  dis++;
  dis++;
  dis++;
 }
 cout<<dis; 
 }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值