Rainbow Trees
Time limit5sMemory limit512 MB
Count rainbow edge colorings of a tree where any two adjacent edges differ and any three consecutive edges all differ, modulo 1e9+9.
- Level
Medium7 of 10
- Topics
- Tree, Greedy, Dynamic programming, Math
- Solved
- No attempts yet
Problem
In graph theory, a tree is a connected undirected simple graph with no cycles. A tree with vertices always has edges.
A path in a tree is a sequence of distinct edges in which every two consecutive edges share a vertex.
You are given a tree with vertices and edges. Paint each edge with one of colors.
A painting is a rainbow coloring if the edges of every path made of 2 edges have different colors and the edges of every path made of 3 edges have different colors. In other words, two consecutive edges always differ in color, and three consecutive edges always use three different colors.
Given the tree and the number of colors , compute the number of rainbow colorings modulo .
Input
The first line contains the number of test cases . Each test case then consists of the following.
- One line with two integers and separated by a space. is the number of vertices of the tree and is the number of available colors.
- lines, one per edge, each with two integers and : the endpoints of that edge. Vertices are numbered from 1 to .
Limits
- Every vertex number is between 1 and , inclusive.
- The given edges always form a tree.
Output
For each test case, print one line in the format Case #X: Y, where is the 1-based test case number and is the answer for that case.
Notes
Take a tree with 4 vertices where one vertex is joined to each of the other three, with 10 colors available. All three edges are pairwise adjacent, so a rainbow coloring must give them three different colors. That leaves colorings.
Now take a tree whose 5 vertices form a single path, with 3 colors available. The first three edges must all differ, which gives choices, and the color of the fourth edge is then forced. So there are 6 rainbow colorings.