题目链接:点击查看
题目大意:给出一棵树,再给出 m 次询问,每次询问给出 x , y , a , b , k ,问如果在点 x 和点 y 之间添加一条边,那么能否从点 a 到点 b 恰好走 k 条边到达,树上的边和点都可以重复经过
题目分析:读完题后没什么思路,但其实稍微转换一下题意就变的非常简单了,题目要求恰好经过 k 条边从点 a 到达点 b ,那么我们思考一下有哪些途径可以从点 a 到达点 b 呢?
- 直接从点 a 到达点 b
- a -> x -> y -> b
- a -> y -> x -> b
其实仔细一想无非只有这三条路可走,每条路径的长度也可以用树上倍增求LCA在logn的时间内解决,现在问题是如何恰好走 k 步呢?其实直接从点 a 到达点 b 后,根据剩余的步数判断就可以了,因为如果剩余的步数为偶数的话,我们可以在点 b 和旁边任意一个点之间反复横跳,最后步数可以恰好抵消掉,相应的,剩余步数为奇数时就不能抵消了
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e5+100;
vector<int>node[N];
int deep[N],dp[N][20],limit;
void dfs(int u,int fa,int dep)
{
deep[u]=dep;
dp[u][0]=fa;
for(int i=1;i<=limit;i++)
dp[u][i]=dp[dp[u][i-1]][i-1];
for(auto v:node[u])
{
if(v!=fa)
dfs(v,u,dep+1);
}
}
int LCA(int x,int y)
{
if(deep[x]<deep[y])
swap(x,y);
for(int i=limit;i>=0;i--)
if(deep[x]-deep[y]>=(1<<i))
x=dp[x][i];
if(x==y)
return x;
for(int i=limit;i>=0;i--)
if(dp[x][i]!=dp[y][i])
{
x=dp[x][i];
y=dp[y][i];
}
return dp[x][0];
}
int dis(int a,int b)
{
int lca=LCA(a,b);
return deep[a]+deep[b]-2*deep[lca];
}
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
//#endif
// ios::sync_with_stdio(false);
int n;
scanf("%d",&n);
limit=log2(n)+1;
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
node[u].push_back(v);
node[v].push_back(u);
}
dfs(1,0,0);
int m;
scanf("%d",&m);
while(m--)
{
int x,y,a,b,k;
scanf("%d%d%d%d%d",&x,&y,&a,&b,&k);
int d1=dis(a,b),d2=dis(a,x)+dis(b,y)+1,d3=dis(b,x)+dis(a,y)+1;
if(k>=d1&&(k-d1)%2==0||k>=d2&&(k-d2)%2==0||k>=d3&&(k-d3)%2==0)
puts("YES");
else
puts("NO");
}
return 0;
}