Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.

The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.

The boys have already chosen three stations ab and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations sft so that the number Grisha will count is as large as possible. They asked you for help.

Input

The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.

The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pimeans that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.

The next q lines contains three integers ab and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

Output

Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations st and f are chosen optimally from the three stations on the i-th day.

Examples

Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2

Note

In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1  2, and Grisha would go on the route 3  1  2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3  1  2. Grisha would see the text at 3 stations.

In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1  2 3, and Grisha would go on the route 2  3 and would see the text at both stations.

题意:给定一个含有N个节点的树,和Q个群问,每一个询问包括三个整数,a,b,c 。 让求出这三个整数构成的两个路径中交点个数的最大值。

思路:

首先我们应该知道这样的问题,如果这三个整数构成了这样的两个路径,a到b,和,c到b  这两个路径。

定义a到b的距离是lab,其他类推。那么这两个路径的交点个数是 ( lab + lbc - lac ) / 2 + 1

那么我们用倍增在线LCA求任意两个节点的最短路径的距离,然后枚举a,b,c分别做为交点的路径情况的最大值即是答案。

细节见代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define dll(x) scanf("%I64d",&x)
#define xll(x) printf("%I64d\n",x)
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define db(x) cout<<"== [ "<<x<<" ] =="<<endl;
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll powmod(ll a,ll b,ll MOD){ll ans=1ll;while(b){if(b&)ans=ans*a%MOD;a=a*a%MOD;b>>=;}return ans;}
inline void getInt(int* p);
const int maxn=;
const int inf=0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
const int N = 1e5+;
std::vector<int> son[N];
int depth[N],fa[N][],in[N],a,b;
// depth[i] -> i 节点的深度
// fa[i][j] -> i 节点向上移动2^j个节点后的祖先
// fa[i][0] -> i 向上移动1个节点后的祖先,即父节点
// in[i] i节点的入度,用来找树根用的。
// a b 为读边用的。
int n;
int m;
void buildtree()
{
for(int i=;i<=n;i++)
{
a=i;
scanf("%d",&b);
son[a].push_back(b);
son[b].push_back(a);
}
}
void dfs(int rt,int prev)
{
depth[rt]=depth[prev]+;
fa[rt][]=prev;
for(int i=;i<;i++)
{
fa[rt][i]=fa[fa[rt][i-]][i-];
}
for(int i=;i<son[rt].size();i++)
{
if(son[rt][i]==prev)
continue;
dfs(son[rt][i],rt);
}
}
int LCA(int x,int y)
{
if(depth[x]<depth[y])
swap(x,y);
for(int i=;i>=;i--)
{
if(depth[x]-(<<i)>=depth[y])
{
x=fa[x][i];
}
}
if(x==y)
{
return x;
}
for(int i=;i>=;i--)
{
if(fa[x][i]!=fa[y][i])
{
x=fa[x][i];
y=fa[y][i];
}
}
return fa[x][];
}
int dist(int a,int b)
{
int u=LCA(a,b);
int L=depth[a]+depth[b]-*depth[u];
return L;
}
int main()
{
// freopen("C:\\Users\\DH_M\\Desktop\\code_io\\in.txt.txt","r",stdin);
// freopen("C:\\Users\\DH_M\\Desktop\\code_io\\out.txt.txt","w",stdout);
scanf("%d",&n);
scanf("%d",&m);
buildtree();
depth[]=-;
int rt=;// root
dfs(rt,rt);
int c;
for(int i=;i<=m;i++)
{
scanf("%d %d %d",&a,&b,&c);
int ans=;
int lab,lbc,lac,l1,l2,l3;
lac=dist(a,c);
lab=dist(a,b);
lbc=dist(b,c);
l1=(lab+lbc-lac)/;
l2=(lab+lac-lbc)/;
l3=(lac+lbc-lab)/;
ans=max(l1,max(l2,l3));
printf("%d\n",ans+);
}
return ;
} inline void getInt(int* p) {char ch;do {ch = getchar();}
while (ch == ' ' || ch == '\n');if (ch == '-') {*p = -(getchar() - '');
while ((ch = getchar()) >= '' && ch <= '') {*p = *p * - ch + '';}}
else {*p = ch - '';while ((ch = getchar()) >= '' && ch <= '')
{*p = *p * + ch - '';}}}

Misha, Grisha and Underground CodeForces - 832D (倍增树上求LCA)的更多相关文章

  1. Codeforces Round #425 (Div. 2) Problem D Misha, Grisha and Underground (Codeforces 832D) - 树链剖分 - 树状数组

    Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations ...

  2. Codeforces 832D - Misha, Grisha and Underground

    832D - Misha, Grisha and Underground 思路:lca,求两个最短路的公共长度.公共长度公式为(d(a,b)+d(b,c)-d(a,c))/2. 代码: #includ ...

  3. Codeforces Round #425 (Div. 2) Misha, Grisha and Underground(LCA)

    Misha, Grisha and Underground time limit per test 2 seconds memory limit per test 256 megabytes inpu ...

  4. Codeforces 832 D Misha, Grisha and Underground

    Misha, Grisha and Underground 题意:Misha 和 Grisha 是2个很喜欢恶作剧的孩子, 每天早上 Misha 会从地铁站 s 通过最短的路到达地铁站 f, 并且在每 ...

  5. Codeforecs Round #425 D Misha, Grisha and Underground (倍增LCA)

    D. Misha, Grisha and Underground time limit per test 2 seconds memory limit per test 256 megabytes i ...

  6. D. Misha, Grisha and Underground 树链剖分

    D. Misha, Grisha and Underground 这个题目算一个树链剖分的裸题,但是这个时间复杂度注意优化. 这个题目可以选择树剖+线段树,时间复杂度有点高,比较这个本身就有n*log ...

  7. 倍增法求lca(最近公共祖先)

    倍增法求lca(最近公共祖先) 基本上每篇博客都会有参考文章,一是弥补不足,二是这本身也是我学习过程中找到的觉得好的资料 思路: 大致上算法的思路是这样发展来的. 想到求两个结点的最小公共祖先,我们可 ...

  8. HDU 2586 倍增法求lca

    How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  9. 倍增法求LCA

    倍增法求LCA LCA(Least Common Ancestors)的意思是最近公共祖先,即在一棵树中,找出两节点最近的公共祖先. 倍增法是通过一个数组来实现直接找到一个节点的某个祖先,这样我们就可 ...

随机推荐

  1. 前后端分离djangorestframework——分页组件

    Pagination 为什么要分页也不用多说了,大家都懂,DRF也自带了分页组件 这次用  前后端分离djangorestframework——序列化与反序列化数据  文章里用到的数据,数据库用的my ...

  2. SQL 删除外键列

    一 SQL删除列的语句是: alter table tableName drop column columnName --(其中,tableName为表名,columnName为列名) 但是,如果某列 ...

  3. window.onunload中使用HTTP请求

    在页面关闭时触发window.onunload 在onunload中要使用http请求,需要使用同步请求: 如: $.ajax({ url: url, async: false }); iframe页 ...

  4. Linux进程调度器概述--Linux进程的管理与调度(十五)

    调度器面对的情形就是这样, 其任务是在程序之间共享CPU时间, 创造并行执行的错觉, 该任务分为两个不同的部分, 其中一个涉及调度策略, 另外一个涉及上下文切换. 1 背景知识 1.1 什么是调度器 ...

  5. MapFileParser.sh: Permission denied

    Unity项目,需要用Xcode运行,结果报了错误. 解决方案: 1.打开终端, 2.输入以下命令: chmod +x   /Users/......./MapFileParser.sh (MapFi ...

  6. ADV190007 - “PrivExchange” 特权提升漏洞的指南

    Microsoft Exchange Server中存在一个特权提升漏洞.成功利用此漏洞的攻击者可能会尝试模仿Exchange服务器的任何其他用户.要利用此漏洞,攻击者需要执行中间人攻击才能将身份验证 ...

  7. NumPy 中的集合运算

    怎样快速找出两个数组中相同的元素? numpy.isin(element,test_elements,assume_unique = False,invert = False ) 计算test_ele ...

  8. Kali 2.0 下 Metasploit 初始化配置

    在kali 2.0中,命令行中直接输入msfconsole 提示不能连接到数据库 ,是由于postgresql 未启动.因此,需要开启postgresql,并且进行postgresql 的初始化配置. ...

  9. LeetCode算法题-Valid Anagram(Java实现)

    这是悦乐书的第198次更新,第205篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第61题(顺位题号是242).给定两个字符串s和t,写一个函数来确定t是否是s的anag ...

  10. 用deepin堆砌工作环境

    用deepin堆砌工作环境 这篇文章记录了我用 deepin 15.5搭建工作环境的过程,供我个人在未来重装系统时参考.对于其他以 deepin 操作系统作为主要工作平台的看官,咱们是相亲相爱的一家人 ...