Tree
Time limit1sMemory limit512 MB
Count labelled trees on N vertices that contain all M given edges, modulo 1e9+7, with N up to 1e9.
- Level
Medium7 of 10
- Topics
- Combinatorics, Union-find, Math, Graph
- Solved
- No attempts yet
Problem
A tree is an undirected graph in which exactly one path connects any two vertices. Equivalently, it is a graph that is connected and has no cycle.
Count the trees you can build on distinguishable vertices. Number the vertices from to , and two trees are different when their edges join different pairs of vertices. For there are 16 trees, shown below.

Write a program that counts the trees on distinguishable vertices that contain all given edges.
Input
The first line contains two integers separated by a space: the number of vertices and the number of edges that the tree must contain. Each of the next lines contains the two endpoints and () of a required edge. The values and are different, and no edge is given twice. It may be impossible to build a tree that contains every given edge.
,
Output
Print the number of trees that contain every given edge. The number can be very large, so print it modulo .
Hint

The picture colours the edge between vertex 1 and vertex 2 red. With 4 vertices, only 8 trees contain that edge.