样例可过,提交#2,#9,#10RE。
本以为是缓冲区开小了,但是输入输出缓冲区都开到8MB了还是RE。
换成cin/cout输入输出就过了。
代码是这个
#include<bits/stdc++.h>
using namespace std;
class IO{
char inbuf[1<<23],*p1=inbuf,*p2=inbuf,obuf[1<<23],*p3=obuf,c;
bool f;
inline void read(int& x){
x=0;
f=false;
for(c=(*p1++);!isdigit(c);c=(*p1++));
for(;isdigit(c);c=(*p1++)) x=(x<<3)+(x<<1)+(c^48);
x=f?-x:x;
}
inline void print(const char x){
*p3++=x;
}
public:
IO(){
p2=(p1+fread(inbuf,1,1<<21,stdin));
}
~IO(){
fwrite(obuf,1,p3-obuf,stdout);
}
template<typename T>
inline IO& operator>>(T& x){
read(x);
return *this;
}
template<typename T>
inline IO& operator<<(const T x){
print(x);
return *this;
}
}io;
const int N=1000010;
struct edge{
int ed,next;
}b[N<<1];
int n,q,tot,nbs[N],dep[N],f[N][22];
inline void swap(int& x,int& y){
int tmp=x;
x=y,y=tmp;
}
inline void addedge(int x,int y){
tot++,b[tot].ed=y,b[tot].next=nbs[x],nbs[x]=tot;
}
void dfs(int k,int fa){
dep[k]=dep[fa]+1;
for(int i=1;(1<<i)<=dep[k];i++) f[k][i]=f[f[k][i-1]][i-1];
for(int i=nbs[k];i;i=b[i].next){
int u=b[i].ed;
if(u==fa) continue;
f[u][0]=k;
dfs(u,k);
}
}
int lca(int x,int y){
if(dep[x]<dep[y]) swap(x,y);//dep[x]>dep[y]
for(int i=20;i>=0;i--){
if(dep[y]<=dep[f[x][i]]) x=f[x][i];
if(x==y) return x;
}
for(int i=20;i>=0;i--)
if(f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
return f[x][0];
}
int dis(int x,int y){
int z=lca(x,y);
return dep[x]-dep[z]+dep[y]-dep[z];
}
int main(){
io>>n>>q;
for(int i=1,x,y;i<n;i++){
io>>x>>y;
addedge(x,y),addedge(y,x);
}
dfs(1,-114514);
for(int i=1,a,b,c,d,x,y;i<=q;i++){
io>>a>>b>>c>>d;
x=lca(a,b),y=lca(c,d);
if(dis(a,y)+dis(b,y)==dis(a,b) or dis(c,x)+dis(d,x)==dis(c,d)) io<<'Y'<<'\n';
else io<<'N'<<'\n';
}
return 0;
}