Make a Forest
Time limit2sMemory limit512 MB
Given N weighted tuples (u,v,w) with distinct weights, build a forest realizing each tuple as a parent-child edge so that every internal node's parent edge is smaller than all its child edges, each node has at most M children, and the number of trees is minimized. Output that minimum tree count.
- Level
Hard8 of 10
- Topics
- Graph, Union-find, Greedy, Sorting
- Solved
- No attempts yet
Problem
In 1736, Leonhard Euler wrote a paper on the Seven Bridges of Konigsberg, which is regarded as the first paper in the history of graph theory. Nowadays, the study of graph theory is considered very important, as shown by the fact that most discrete mathematics textbooks contain a chapter on graph theory.
This problem concerns graph theory, especially trees and forests. Given tuples , construct a forest with the minimum possible number of trees that satisfies all seven requirements below:
- Each tree in the forest is a rooted tree.
- Each node in the forest has a value .
- Each edge in the forest has a value .
- Each tuple appears exactly once in the forest as a parent-child pair (parent node and child node ) with , , and .
- For every node that is neither the root nor a leaf, is smaller than every , where is the parent of and is a child of .
- Every node in the forest has at most children.
- The forest contains exactly edges.
To simplify the problem, all values are guaranteed to be distinct: no two tuples share the same .
Output the number of trees in such a forest whose number of trees is minimum.
Input
The first line contains two integers (), the number of tuples and the maximum number of children of each node in the forest. Each of the next lines contains three integers (, ), describing the tuple .
Output
Print one integer in a line: the number of trees in a forest with the minimum possible number of trees satisfying the given requirements.
Hint
Explanation for the 1st sample case:

For the first sample, this forest is the only forest satisfying all the requirements. It contains 2 trees.

On the other hand, this forest does not satisfy the requirements because:
- Node violates requirement 5, since is larger than and .
- Node violates requirement 6, since it has 3 children (note that is 2).
- The forest has 6 edges while (violating requirement 7).
Violating even one requirement already makes the forest invalid.