A Game with Two Trees
Time limit2sMemory limit512 MB
Given two trees with marked special nodes, add one edge between a node of each tree and sum the perfect paths for every pair, weighted by i+j, modulo 1e9+7.
- Level
Hard8 of 10
- Topics
- Tree, DFS, Divide and conquer
- Solved
- No attempts yet
Problem
Albert is playing a game with two trees. The first tree has nodes, written . The nodes in are called "special". The second tree has nodes, written . The nodes in are special.
The figure below shows an example where both trees have 3 nodes (). has 3 nodes and has 1 node. Special nodes are drawn with double lines.

Pick one node from each tree and connect them with an edge. Let be the tree formed by adding the edge to . The score of is the number of simple paths in that contain exactly one node from and exactly one node from . Call such a path a "perfect path".
In the example, , , and . For , the only perfect path is . For , there are three perfect paths: , , and . For , the only perfect path is .

The values , , , , , and are obtained the same way.
Computing for one pair is easy, so Albert wants to compute . In the example, this value is 60.
Given both trees, compute .
Input
The first line contains the number of test cases .
The first line of each test case contains and , separated by a space. The second line contains the indices of the nodes in , separated by spaces. The next lines each contain two integers, separated by a space, describing an edge of .
Then comes a line with and , separated by a space. The next line contains the indices of the nodes in , separated by spaces. The last lines each contain two integers describing an edge of .
Output
For each test case, print modulo on its own line.
Constraints
- No element appears twice in .
- No element appears twice in .
- Both and are valid trees.