http://www.lydsy.com/JudgeOnline/problem.php?id=1787

题目描述

输入

输出

样例输入

6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6

样例输出

5 2
2 5
4 1
6 0

提示

易发现:三个点两两求出LCA,一定至少有两个LCA相等

    若只有两个相等,那聚集点就是剩下的LCA

    若三个相等,那聚集点就是LCA

 #include <algorithm>
#include <cstdio>
#include <vector> using namespace std; const int N(1e5*+);
vector<int>vec[N];
int n,m,x,y,z;
int anspoint,anssum;
int deep[N],dad[N],size[N],top[N]; void DFS(int x)
{
size[x]=; deep[x]=deep[dad[x]]+;
for(int i=;i<vec[x].size();i++)
if(dad[x]!=vec[x][i])
{
dad[vec[x][i]]=x;
DFS(vec[x][i]);
size[x]+=size[vec[x][i]];
}
} void DFS_(int x)
{
int t=; if(!top[x]) top[x]=x;
for(int i=;i<vec[x].size();i++)
if(vec[x][i]!=dad[x]&&size[t]<size[vec[x][i]]) t=vec[x][i];
if(t) top[t]=top[x],DFS_(t);
for(int i=;i<vec[x].size();i++)
if(vec[x][i]!=dad[x]&&t!=vec[x][i]) DFS_(vec[x][i]);
} int LCA(int x,int y)
{
while(top[x]!=top[y])
{
if(deep[top[x]]<deep[top[y]]) swap(x,y);
x=dad[top[x]];
}
if(deep[x]>deep[y]) swap(x,y);
return x;
} int main()
{
scanf("%d%d",&n,&m);
for(int i=;i<n;i++)
{
scanf("%d%d",&x,&y);
vec[x].push_back(y);
vec[y].push_back(x);
}
DFS(); DFS_();
for(;m;m--)
{
scanf("%d%d%d",&x,&y,&z);
anspoint=LCA(x,y)^LCA(x,z)^LCA(y,z);
anssum =deep[x]+deep[anspoint]-(deep[LCA(x,anspoint)]<<);
anssum+=deep[y]+deep[anspoint]-(deep[LCA(y,anspoint)]<<);
anssum+=deep[z]+deep[anspoint]-(deep[LCA(z,anspoint)]<<);
printf("%d %d\n",anspoint,anssum);
}
return ;
}

最新文章

  1. [Hadoop in Action] 第7章 细则手册
  2. 理解和使用 JavaScript 中的回调函数
  3. Mybatis错误调试(二)
  4. 修改FFMpeg源码—捕获丢包
  5. 如何使用UIAutomation进行iOS 自动化测试(Part I)
  6. 贴近浏览器窗口右侧的jqueryui dialog快速从左侧调整大小时对话框大小设置不准确的问题
  7. Vuex 学习笔记
  8. 浅谈ES6
  9. mySQL的安装和基础使用及语法教程
  10. Linux安装kubernetes
  11. Python科学计算基础包-Numpy
  12. 使用4K分辨率,然后放大DIP200%,软件界面异常.
  13. python入门之小栗子
  14. Burpsuite安全测试测试指导
  15. webpack优化以及node版本
  16. C#的值传递与引用传递
  17. 11.8Django中的组件content_type
  18. 关于mysql的压测sysbench
  19. mysql数据库分区功能及实例详解
  20. SAP HANA S4 FI TABLE表结构

热门文章

  1. C#--文件操作的一些技巧
  2. 洛谷 U6254 最低费用
  3. HttpClient异步请求Post传递Json
  4. [Beginning SharePoint Designer 2010]Chapter 3 分析SharePoint页面
  5. POSIX 线程编程(二)线程建立与终止
  6. angularjs1-2,作用域、代码压缩
  7. 使用fiddler模拟http get
  8. C#读出文本文件内容,遍历数组筛选出 含有汉字对应的拼音字符
  9. docker compose线下安装
  10. Noip蒟蒻专用模板