仓鼠找sugar--lca+图论判断点在路径

1.题目大意就是在树上,找a->b和c->d的最短路径中是不是有重合的点

2.x=lca(a,b),y=lca(c,d),

要是路径重合,两条路径任在其中选一,他们的lca一定是在x到y这条路上的,这条路要么是a->b的,要么是c->d的,具体要看谁的lca深度大

3.check函数判断该点在线段是点到两端点的距离==线段长度

P3398 仓鼠找 sugar - 洛谷

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
#define N 100011
typedef  long long ll;
typedef pair<int,int> pii;
int n,k;
vector<int> mp[N];
int d[N],fa[N][25];
ll sum[N];
void dfs(int u,int f)
{
	d[u]=d[f]+1;
	fa[u][0]=f;
	for(int i=1;i<=20;i++)
	{
		fa[u][i]=fa[fa[u][i-1]][i-1];
	}
	for(auto v:mp[u])
	{
		if(v!=f)
		{
			sum[v]=sum[u]+1;
			dfs(v,u);
		}
	}
}
int lca(int s,int t)///最近公共祖先,也是路径中深度最小的点 
{
	if(d[s]<d[t]) swap(s,t);
	for(int i=20;i>=0;i--)
	{
		if(d[fa[s][i]]>=d[t])
		{
			s=fa[s][i];
		}
	}
	if(s==t)return s;
	for(int i=20;i>=0;i--)
	{
		if(fa[s][i]!=fa[t][i])
		{
			s=fa[s][i];
			t=fa[t][i];
		}
	}
	return fa[s][0];
}
ll an;
int dist(int a,int b)///求ab距离函数 
{
	return sum[a]+sum[b]-2*sum[lca(a,b)];
}
bool check(int a,int b,int c,int d)
{
	int w=lca(a,b);
	int e=lca(c,d);
	if(w==e) return true;
	if(sum[w]<sum[e])///先判断a->b和c->d的深度 
	{	
		///深度大的lca在小的路径上 
		///判断重合的条件,就是到两端点的距离等于线段长度 
		if(dist(a,e)+dist(e,b)==dist(a,b)) return true;
		else return false;
	}
	else
	{
		if(dist(c,w)+dist(w,d)==dist(c,d)) return true;
		else return false;
	}
}
void solve()
{
	cin>>n>>k;
	for(int i=0;i<n-1;i++)
	{
		int u,v;
		cin>>u>>v;
		mp[u].push_back(v);
		mp[v].push_back(u);
	}
	dfs(1,0);
	while(k--)
	{
		int a,b,c,dd;
		cin>>a>>b>>c>>dd;
		if(check(a,b,c,dd))
		cout<<"Y";
		else cout<<"N";
		cout<<endl;
	}
} 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();
    return 0;
}
相关推荐
钮钴禄·爱因斯晨17 小时前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
heeheeai2 天前
kotlin图算法
算法·kotlin·图论
杨小码不BUG4 天前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
(❁´◡`❁)Jimmy(❁´◡`❁)5 天前
【Trie】 UVA1401 Remember the Word
算法·word·图论
qq_418247886 天前
论文阅读:TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
论文阅读·人工智能·深度学习·图论
希望201715 天前
图论基础知识
算法·图论
行走的bug...16 天前
用图论来解决问题
算法·图论
Athenaand16 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
_Coin_-17 天前
算法训练营DAY60 第十一章:图论part11
算法·图论
Athenaand17 天前
代码随想录算法训练营第62天 | Floyd 算法精讲、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结
算法·图论