仓鼠找sugar

题目描述

小仓鼠的和他的基(mei)友(zi)sugar住在地下洞穴中,每个节点的编号为1~n。地下洞穴是一个树形结构。这一天小仓鼠打算从从他的卧室(a)到餐厅(b),而他的基友同时要从他的卧室(c)到图书馆(d)。他们都会走最短路径。现在小仓鼠希望知道,有没有可能在某个地方,可以碰到他的基友?

小仓鼠那么弱,还要天天被zzq大爷虐,请你快来救救他吧!

输入格式

第一行两个正整数n和q,表示这棵树节点的个数和询问的个数。

接下来n-1行,每行两个正整数u和v,表示节点u到节点v之间有一条边。

接下来q行,每行四个正整数a、b、c和d,表示节点编号,也就是一次询问,其意义如上。

输出格式

对于每个询问,如果有公共点,输出大写字母“Y”;否则输出“N”。

输入输出样例

输入 #1
5 5
2 5
4 2
1 3
1 4
5 1 5 1
2 2 1 4
4 1 3 4
3 1 1 5
3 5 1 4
输出 #1
Y
N
Y
Y
Y
说明/提示

本题时限1s,内存限制128M,因新评测机速度较为接近NOIP评测机速度,请注意常数问题带来的影响。

20%的数据 n<=200,q<=200

40%的数据 n<=2000,q<=2000

70%的数据 n<=50000,q<=50000

100%的数据 n<=100000,q<=100000

.
.
.
.
.
.
程序:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int n,m,dep[100007],top[100007],fa[100007],size[100007],hson[100007],head[100007],cnt;

struct Node 
{
	int to,next;
}e[100007<<1];

int read()
{
    char ch=getchar(); 
	int x=0;
	bool flag=false;
    while (ch<'0'||ch>'9') 
	{
		if( ch=='-' ) flag=true;
		ch=getchar();
	}
    while (ch>='0'&&ch<='9') 
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
    return flag?-x:x;
}

void add(int x,int y)
{
    e[++cnt].to=y;e[cnt].next=head[x];head[x]=cnt;
    e[++cnt].to=x;e[cnt].next=head[y];head[y]=cnt;
}

void dfs1(int x,int last)
{
    size[x]=1;
    for (int i=head[x];i;i=e[i].next)
	{
        int y=e[i].to;
        if (y==last) continue;
        dep[y]=dep[x]+1;
		fa[y]=x;
        dfs1(y,x);
		size[x]+=size[y];
        if (size[y]>size[hson[x]]) hson[x]=y;
    }
}

void dfs2(int x,int nowtop)
{
    top[x]=nowtop;
    if (!hson[x]) return;
    dfs2(hson[x],nowtop);
    for(int i=head[x];i;i=e[i].next)
	{
        int y=e[i].to;
        if (y==fa[x]||y==hson[x]) continue;
        dfs2(y,y);
    }
}

int lca(int x,int y)
{
	while (top[x]!=top[y])
	{
		if (dep[top[x]]<dep[top[y]]) swap(x,y);
		x=fa[top[x]];
	}
    return dep[x]<dep[y]?x:y;
}

bool check(int a,int b,int c,int d)
{
    int lca1=lca(a,b),lca2=lca(c,d);
    if (dep[lca1]>=dep[lca2])
	{
        if (lca(c,lca1)==lca1) return true;
        if (lca(d,lca1)==lca1) return true;
    } else
	{
        if (lca(a,lca2)==lca2) return true;
        if (lca(b,lca2)==lca2) return true;
    }
    return false;
}

int main()
{
    n=read();m=read();
    for (int i=1;i<n;i++)
    	add(read(),read());
    dep[1]=1;dfs1(1,0);dfs2(1,1);
    int a,b,c,d;
    for (int i=1;i<=m;i++)
	{
        a=read();b=read();c=read();d=read();
        if (check(a,b,c,d)) cout<<'Y'<<endl; else cout<<'N'<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值