Roads
Time limit1sMemory limit128 MB
Decide whether the graph has a spanning tree with exactly K gravel edges, where each road is gravel or concrete.
- Level
Medium7 of 10
- Topics
- Graph, Minimum spanning tree, Union-find, Greedy
- Solved
- No attempts yet
Problem
The Kingdom of New Asia has villages connected by roads. Some roads are paved with gravel and others with concrete. Keeping every road toll-free is far too expensive, so the king decides on a new road-maintenance plan.
The king wants the number of free roads to be as small as possible, while still guaranteeing that between any two villages there is exactly one path using only free roads. In other words, the free roads must form a single tree that connects all villages. Moreover, because the king enjoys walking on gravel, he wants exactly of the free roads to be gravel roads.
For example, suppose the villages and roads are as in Figure 1a. If the king wants exactly free gravel roads, then making roads free (Figure 1b) satisfies the requirements: (1) all villages are connected by free roads, (2) the number of free roads is as small as possible, and (3) exactly two of them, namely and , are gravel. Because such a plan exists, the answer in this case is possible.

Figure 1: (a) An example of the villages and roads of New Asia. Solid lines are concrete roads and dashed lines are gravel roads. (b) A maintenance plan with exactly two free gravel roads; only the free roads are shown.
Given the roads of the kingdom and the number of free gravel roads the king wants, write a program that decides whether a maintenance plan meeting the king's requirements exists.
Input
The first line contains three space-separated integers.
- : the number of villages ()
- : the number of roads ()
- : the number of gravel roads the king wants to keep free ()
Each of the next lines describes road (for from to ); line describes road with three space-separated integers.
- and : the two villages connected by road (villages are numbered to )
- : the type of road ; means a gravel road and means a concrete road.
There is at most one road between any pair of villages.
Output
Print possible on a single line if a maintenance plan meeting the king's requirements exists, and no solution otherwise.