题目链接:http://codeforces.com/contest/466/problem/E
题意:
简化下题意(可以自己看看,简化的太严重了),给你n个节点的树和m个操作。
1、a->b这条链上所有的数都拥有v(v是递增的,)。
2、问c节点是否拥有v。
题解:
(自己先简化了题意)这道题直接简化成了判断c在不在某条链上。我们对树直接跑一遍dfs,记录下每个节点的进dfs的时间l[x],和出dfs的时间r[x]。
判断u是v的祖先的话,直接判断l[u]<=l[v]&&r[v]<=r[u]是否成立就可以了。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<cstdlib>
#include<cmath>
#define PI 2*asin(1.0)
#define LL long long
#define pb push_back
#define pa pair<int,int>
#define clr(a,b) memset(a,b,sizeof(a))
#define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r
#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)
#define key_value ch[ch[root][1]][0]
const LL MOD = 9973;
const int N = 1e5+15;
const int maxn = 8e3+15;
const int letter = 130;
const LL INF = 1e18;
const double pi=acos(-1.0);
const double eps=1e-10;
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m;///1e5
int tot,head[N],father[N];
int l[N],r[N],vis[N];
int cpar=0,tot_t,num;
struct edges{
int to,next;
}e[N];
struct node{
int up,down;
}ps[N];
struct cnode{
int id,val;
}vv[N];
int Find(int x){
if(x==father[x]) return x;
return father[x]=Find(father[x]);
}
void addedges(int u,int v){
e[tot].to=v,e[tot].next=head[u],head[u]=tot++;
}
void init(int n){
for(int i=1;i<=n;i++) father[i]=i;
num=tot_t=tot=0,clr(head,-1);
}
void dfs(int x){
l[x]=++tot_t;
vis[x]=1;
for(int i=head[x];i!=-1;i=e[i].next) dfs(e[i].to);
r[x]=tot_t;
}
bool ok(int fa,int so){
return l[fa]<=l[so]&&r[so]<=r[fa];
}
int main(){
int op,x,y;
scanf("%d%d",&n,&m);
init(n);
for(int i=0;i<m;i++){
scanf("%d%d",&op,&x);
if(op==1){
scanf("%d",&y);
father[x]=y;
addedges(y,x);
vis[x]=1;
}
else if(op==2){
ps[++cpar].down=x;
ps[cpar].up=Find(x);
}
else {
scanf("%d",&y);
vv[++num].val=x,vv[num].id=y;
}
}
for(int i=1;i<=n;i++) {
if(!vis[i]) dfs(i);
}
for(int i=1;i<=num;i++){
if(ok(ps[vv[i].id].up,vv[i].val)&&ok(vv[i].val,ps[vv[i].id].down))
puts("YES");
else puts("NO");
}
return 0;
}
/*
4 6
1 4 3
2 4
1 3 1
2 4
3 1 1
3 1 2
*/