Tree-Query

0

0 votes
Sparse Table, Hard, Tree, Life-cycle assessment, Loops, Segment tree
Problem

Mike has a tree with n nodes. On each node u, there is an integer cu.

A number is interesting if and only if its digits in the decimal representation are distinct. For example, the numbers 1546,198,1 are interesting but the numbers 1222,1001,9011 are not.

Consider a length-k path on the tree P1,P2,...,Pk, a subpath is determined by two parameters l and r (1lrk). The subpath starting from lth node and ending on rth node is Pl,Pl+1,...,Pr. Therefore, a length-k path has k×(k+1)2 subpaths.

He has q queries. Each query consists of two numbers, u and v. Considering the path starting from u and ending at v, he wants to know the number of interesting subpaths. A subpath is interesting if and only if there exists at least one node on the subpath whose assigned number is interesting.

Input

The first line contains a number n (1n500000).

The next line contains n numbers c1,c2,...,cn - ci is the assigned number to node i (1ci109).

The next n1 lines contains two numbers separated by space.The (i+2)th line contains ai,bi (1ai,bin) representing that there is an edge from the node ai to the node bi.

The next line contains a number q (1q500000).

The next q lines contains two numbers separated by space.The (n+1+i)th line contains ui,vi (1ui,vin).

Output

Output q lines. The ith line must contain the answer for the ith query.

Sample Input
8
1 1 11 11 11 1 11 11
1 2
2 4
2 8
1 3
3 5
3 6
3 7
5
4 7
4 6
8 5
2 3
3 5
Sample Output
11
13
11
5
0
Time Limit: 4
Memory Limit: 1024
Source Limit:
Explanation

For first query, there are 11 interesting subpaths in the path starting from 4 and ending at 7.

Editor Image

?