A Particle on the Tree
Time limit1sMemory limit128 MB
For each query edge (U,V) and final color C, count pairs (start, end) whose shortest path uses that edge in that direction and whose arrival color matches C.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Prefix sum, Math
- Solved
- No attempts yet
Problem

A tree is a connected graph with no cycle. The picture above shows a tree shaped particle accelerator and one special particle placed on a vertex of it. This particle, called an RB particle, is red while it is stable. Once it becomes unstable its color changes every second: red turns black, and black turns red.
Taekhee runs a simple experiment with it. He first fixes a start vertex and an end vertex inside the accelerator, takes one stable particle, makes it unstable, and puts it on the start vertex. That preparation takes no time. Right after that the particle moves toward the end vertex along a shortest path, and crossing one edge takes exactly 1 second.
Taekhee ran experiments but forgot to write the results down. For each experiment he remembers two things: that the particle crossed the edge between vertices and in the direction from to , and the color of the particle when it arrived at the end vertex.
Restoring the report means counting, for each experiment, how many (start vertex, end vertex) pairs agree with what he remembers. Compute that count for him.
Input
The first line has the number of vertices of the accelerator () and the number of experiments ().
Each of the next lines has two vertices joined by an edge. (, )
Each of the next lines has the information known about one experiment as . (, is 0 or 1, )
This means that in that experiment the particle crossed the edge between and in the direction from to , and the color at the end vertex was red when and black when .
The particle is always red at the start vertex. For every and given in an experiment, the tree is guaranteed to contain the edge between and .
The accelerator given in the input is always a valid tree.
Output
Print lines.
On line , print the number of distinct (start vertex, end vertex) pairs that were possible in experiment .
The value can exceed the range of a 32 bit signed integer during the computation.