Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define filer() freopen("in.txt","r",stdin)
- #define filew() freopen("out.txt","w",stdout)
- #include<iostream>
- #include<stdio.h>
- #include<string.h>
- #include<math.h>
- #include<algorithm>
- #include<queue>
- #include<stack>
- #include<string>
- #include<vector>
- #include <map>
- #define INF 1<<29
- #define PI pair<int,int>
- #define f first
- #define s second
- #define SET(a, x) memset((a), (x), sizeof(a))
- #define pb push_back
- #define i64 long long
- #define EPS (1e-9)
- #define MAXN 100000
- #define LOGMAXN 18
- using namespace std;
- typedef vector<int> VI;
- typedef vector<PI> vii;
- //i64 INF=(i64)((i64)1<<(i64)59);
- int N,Q;
- int T[100009];
- int P[MAXN][LOGMAXN],L[MAXN+10];
- vector<int>adj[MAXN+10];
- void DFS(int u)
- {
- int i,j,sz=adj[u].size(),v;
- for(i=0;i<sz;i++)
- {
- v=adj[u][i];
- if(v==P[u][0])continue;
- L[v]=L[u]+1;
- //T[v]=u;
- P[v][0]=u;
- DFS(v);
- }
- }
- void process3( )
- {
- int i, j;
- //we initialize every element in P with -1
- /*for (i = 0; i < N; i++)
- for (j = 0; 1 << j < N; j++)
- P[i][j] = -1;*/
- //the first ancestor of every node i is T[i]
- /* for (i = 0; i < N; i++)
- P[i][0] = T[i];*/
- //bottom up dynamic programing
- for (j = 1; 1 << j < N; j++)
- for (i = 0; i < N; i++)
- if (P[i][j - 1] != -1)
- P[i][j] = P[P[i][j - 1]][j - 1];
- }
- int query( int p, int q)
- {
- int tmp, log, i;
- //if p is situated on a higher level than q then we swap them
- if (L[p] < L[q])
- tmp = p, p = q, q = tmp;
- //we compute the value of [log(L[p)]
- for (log = 1; 1 << log <= L[p]; log++);
- log--;
- //we find the ancestor of node p situated on the same level
- //with q using the values in P
- for (i = log; i >= 0; i--)
- if (L[p] - (1 << i) >= L[q])
- p = P[p][i];
- return p;
- if (p == q)
- return p;
- //we compute LCA(p, q) using the values in P
- for (i = log; i >= 0; i--)
- if (P[p][i] != -1 && P[p][i] != P[q][i])
- p = P[p][i], q = P[q][i];
- return P[p][0];
- }
- int main()
- {
- //filer();
- int cas=0;
- int i,j,x,y,root;
- //SET(P,-1);
- scanf("%d%d",&N,&Q);
- scanf("%d",&root);
- for (i = 0; i < N; i++)
- for (j = 0; 1 << j < N; j++)
- P[i][j] = -1;
- L[root]=1;
- for(i=1;i<N;i++)
- {
- scanf("%d%d",&x,&y);
- adj[x].pb(y);
- adj[y].pb(x);
- //T[y]=x;
- }
- DFS(ad);
- process3();
- while(Q--)
- {
- scanf("%d%d",&x,&y);
- if(L[x]==L[y])
- {
- printf("0\n");
- continue;
- }
- int lca=query(x,y);
- if(lca==y)printf("1\n");//cout<<"1"<<endl;
- else if(lca==x)printf("-1\n");//cout<<"-1"<<endl;
- else printf("0\n");//cout<<"0"<<endl;
- }
- return 0;
- }
- /*
- Test Case:
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement