C Borrow Classroom

链接:https://ac.nowcoder.com/acm/contest/5086/C

题意+思路:给出一棵树,给出三个点tmp1,tmp2,tmp3;

       当tmp1跟tmp3最近祖先为1时:

        if(LCA(tmp1,tmp3)==1){

          if(judgea<judgeb) printf("YES\n");

          else printf("NO\n");

        }

      不为1时

        else{

          if(judgea<=judgeb) printf("YES\n");

          else printf("NO\n");

        }

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e5+10;
 4 struct node
 5 {
 6     int v,nxt;
 7 }G[maxn<<1];
 8 int head[maxn]; int num;
 9 int dis[maxn];
10 int depth[maxn];
11 int fa[maxn][30];
12 void add(int u,int v)
13 {
14     G[++num].v=v;G[num].nxt=head[u];head[u]=num;
15 }
16 void dfs1(int u,int fa,int step)
17 {
18     dis[u]=step;
19     for(int i=head[u];i;i=G[i].nxt){
20         int v=G[i].v;
21         if(v==fa) continue;
22         dfs1(v,u,step+1);
23     }
24 }
25 void dfs2(int prev,int rt){
26     depth[rt]=depth[prev]+1;
27     fa[rt][0]=prev;
28     for(int i=1;i<20;i++)
29         fa[rt][i]=fa[fa[rt][i-1]][i-1];
30     for(int i=head[rt];i;i=G[i].nxt){
31         int v=G[i].v;
32         if(v==prev) continue;
33         dfs2(rt,v);
34     }
35 }
36 int LCA(int x,int y){
37     if (depth[x]<depth[y])
38         swap(x,y);
39     for (int i=19;i>=0;i--)
40         if (depth[x]-(1<<i)>=depth[y])
41             x=fa[x][i];
42     if (x==y)
43         return x;
44     for (int i=19;i>=0;i--)
45         if (fa[x][i]!=fa[y][i])
46             x=fa[x][i],y=fa[y][i];
47     return fa[x][0];
48 }
49 void init()
50 {
51     memset(fa,0,sizeof(fa));
52     memset(dis,0,sizeof(dis));
53     memset(depth,0,sizeof(depth));
54     memset(head,0,sizeof(head));
55     num=0;
56 }
57 int main()
58 {
59     int T;
60     scanf("%d",&T);
61     while(T--){
62         init();
63         int n,q;
64         scanf("%d",&n);scanf("%d",&q);
65         for(int i=1;i<n;i++){
66             int u,v;
67             scanf("%d%d",&u,&v);
68             add(u,v);
69             add(v,u);
70         }
71         dfs1(1,0,0);
72         dfs2(0,1);
73         while(q--){
74             int tmp1,tmp2,tmp3;
75             scanf("%d%d%d",&tmp1,&tmp2,&tmp3);
76             int tmp=LCA(tmp2,tmp3);
77            // printf("tmp:%d\n",tmp);
78             int judgea=dis[tmp1];
79             int judgeb=dis[tmp3]+(dis[tmp2]+dis[tmp3]-2*dis[tmp]);
80            // printf("%d %d\n",judgea,judgeb);
81             if(LCA(tmp1,tmp3)==1){
82                 if(judgea<judgeb) printf("YES\n");
83                 else printf("NO\n");
84             }
85             else{
86                 if(judgea<=judgeb) printf("YES\n");
87                 else printf("NO\n");
88             }
89         }
90     }
91     return 0;
92 }
View Code

 

posted @ 2020-05-13 18:09  古比  阅读(97)  评论(0编辑  收藏  举报