Bridge Construction Planning
Time limit1sMemory limit256 MB
Find the cheapest spanning tree that uses exactly k edges from company A and the rest from company B, or report that none exists.
- Level
Medium7 of 10
- Topics
- Minimum spanning tree, Binary search
- Solved
- No attempts yet
Problem
A city is made up of many small islands, and its citizens live on those islands. Moving between islands requires a ferry, which the citizens find inconvenient. The mayor decided to build bridges that connect all the islands.
The city has two construction companies, A and B. The mayor asked both for quotes, and every proposal that came back has the form "company A (or company B) builds a bridge between island and island for hundred million yen".
The mayor wants to accept part of the proposals and end up with the cheapest plan. Accepting too many proposals from one company could bankrupt the other, and the city has only these two construction companies, so that outcome is unwelcome. To avoid complaints about wasteful construction, the mayor can accept only the smallest number of bridges that connects all the islands, that is of them. The mayor therefore decided to accept exactly proposals from company A and exactly proposals from company B.
Write a program that computes the cost of the cheapest plan meeting these conditions. The cost of a plan is the sum of the costs written in the accepted proposals.
Input
The input consists of several datasets, at most 30 of them. Each dataset has the following format.
n m k
u1 v1 w1 l1
...
um vm wm lm
The first line holds three integers , , , where is the number of islands, is the total number of proposals, and is the number of proposals to order from company A (, , ). Islands are numbered 1 through .
Each of the next lines holds one proposal as three integers , , and one character , where and are the two islands the bridge joins, is the cost of the bridge in hundred million yen, and is the name of the company that submitted the proposal (, , , and is 'A' or 'B'). Every bridge joins two distinct islands, so . A company submits at most one proposal per pair of islands, so if and then .
The end of the input is a line with three zeros separated by single spaces.
Output
For each dataset, print the cost of the cheapest plan, in hundred million yen, as a single integer on its own line. If no plan meets the conditions, print -1.