Evanyou Blog 彩带

  题目传送门

仓鼠找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


  分析:

  一道有点意思的题目。

  首先我们需要知道这样一条性质,树上两条路径相交,则必定其中一条路径起点终点的$LCA$在另一条路径上。如果知道了这条性质就只需要求$LCA$就行了。(这里博主用树剖求的$LCA$)

  Code:

  

//It is made by HolseLee on 4th Nov 2018
//Luogu.org P3398
#include<bits/stdc++.h>
using namespace std;

const int N=1e5+7;
int n,m,dep[N],top[N],fa[N],siz[N],hson[N],head[N],cnte;
struct Node { int to,nxt; }e[N<<1];

inline 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;
}

inline void add(int x,int y)
{
    e[++cnte].to=y, e[cnte].nxt=head[x], head[x]=cnte;
    e[++cnte].to=x, e[cnte].nxt=head[y], head[y]=cnte;
}

void dfs1(int x,int las)
{
    siz[x]=1;
    for(int i=head[x],y; i; i=e[i].nxt) {
        y=e[i].to;
        if( y==las ) continue;
        dep[y]=dep[x]+1, fa[y]=x;
        dfs1(y,x); siz[x]+=siz[y];
        if( siz[y]>siz[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],y; i; i=e[i].nxt) {
        y=e[i].to;
        if( y==fa[x] || y==hson[x] ) continue;
        dfs2(y,y);
    }
}

inline 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;
}

inline 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) ) puts("Y");
        else puts("N");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cytus/p/9905560.html