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-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
2019-07-06 18:34:06
Range of the weight is big and using map will get timelimit. Use compression.
2019-07-04 16:47:21
10 1
1 2 3 4 5 6 7 8 9 10
2 1
3 2
4 2
5 4
6 2
7 6
8 3
9 1
10 2
1 3

ans:3

10 1
1 2 3 4 5 6 7 8 9 10
2 1
3 1
4 2
5 4
6 3
7 5
8 2
9 4
10 7
5 9

ans:3
2018-11-28 21:04:37
What is the Limit of Weight???????????
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.