No.2337 Equidistant
Problem Statement
There is a tree with $N$ vertices, and the vertices are numbered from $1$ to $N$. The $i$-th ($1 \leq i \leq N - 1$) edge connects vertex $A_i$ and vertex $B_i$.
For $2$ vertices $u, v$ of the tree, let $d(u,v)$ be the number of edges traversed when going from vertex $u$ to vertex $v$ using the minimum number of edges.
You are given $Q$ queries.
In the $i$-th ($1 \leq i \leq Q$) query, 2 vertices $S_i, T_i$ of the tree are given. Find the number of vertices $X$ of the tree such that $d(X,S_i)=d(X,T_i)$.
Input
The input is given from standard input in the following format.
$N$ $Q$
$A_1$ $B_1$
$A_2$ $B_2$
$\vdots$
$A_{N-1}$ $B_{N-1}$
$S_1$ $T_1$
$S_2$ $T_2$
$\vdots$
$S_Q$ $T_Q$
Output
Print $Q$ lines to standard output. On the $i$-th ($1 \leq i \leq Q$) line, print the answer to the $i$-th query.
Print a newline at the end.
Constraints
The input satisfies the following constraints.
- $2 \leq N \leq 200\,000$
- $1 \leq Q \leq 200\,000$
- $1 \leq A_i \leq N$ ($1 \leq i \leq N-1$)
- $1 \leq B_i \leq N$ ($1 \leq i \leq N-1$)
- The given graph is a tree.
- $1 \leq S_i \leq N$ ($1 \leq i \leq Q$)
- $1 \leq T_i \leq N$ ($1 \leq i \leq Q$)
- $S_i \neq T_i$ ($1 \leq i \leq Q$)
- All input values are integers.
Sample
Sample 1
Input
7 3 1 2 1 3 2 4 2 5 3 6 3 7 2 3 1 2 4 7
Output
1 0 1
In query $1$, the only $X$ such that $d(X,2)=d(X,3)$ is $1$, so print $1$ on line $1$.
In query $2$, no $X$ such that $d(X,1)=d(X,2)$ exists, so print $0$ on line $2$.
In query $3$, the only $X$ such that $d(X,4)=d(X,7)$ is $1$, so print $1$ on line $3$.
提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。
SSRS
ei1333333
Nachia