COT2 - Count on a tree II

You are given a tree with N nodes. The tree nodes are numbered from 1 to N. Each node has an integer weight.

We will ask you to perform the following operation:

  • u v : ask for how many different integers that represent the weight of nodes there are on the path from u to v.

Input

In the first line there are two integers N and M. (N <= 40000, M <= 100000)

In the second line there are N integers. The i-th integer denotes the weight of the i-th node.

In the next N-1 lines, each line contains two integers u v, which describes an edge (u, v).

In the next M lines, each line contains two integers u v, which means an operation asking for how many different integers that represent the weight of nodes there are on the path from u to v.

Output

For each operation, print its result.

Example

Input:
8 2
105 2 9 3 8 5 7 7
1 2
1 3
1 4
3 5
3 6
3 7
4 8
2 5
7 8

Output:
4
4

Added by:Fotile
Date:2012-02-17
Time limit:1.207s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Just for fun...

hide comments
2020-09-09 15:06:22
Getting WA on test case 10
2020-08-10 09:59:20
Do any know CDQ algo which is also a algo originated from CN?
2020-05-05 23:25:29
The only part missing in the problem statement is the range of the weight which is 1 <= w <= 2^31 - 1.
Coordinate compression is needed.
2020-04-22 09:19:35
Anybody solved this problem in Java? I tried implementating Mo's algo in Java but getting TLE, tried all kinds of optimizations.
2020-04-18 08:05:36
@hacker_sk: You saved my life. Thanks. Admin should update the range of N.
2020-04-14 15:55:05
Constraints are as it is given in the problem itself .
Expected Time Complexity is O(max(NlogN,M*sqrt(N)))
2020-04-06 22:51:21 hacker_sk
NOTE: N <= 100000 (not 40000, got seg fault and wa because of this) and weight <= 2^31 - 1.
2020-03-25 04:49:02
Thanks @bekh compression overcomes TLE
2020-03-20 19:31:16
Input has multiple test cases. Read until end of file...
2020-02-11 07:25:31
if using mos algo then use block size 500
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.