Love That Only Fails for Me
Time limit2sMemory limit256 MB
Find the minimum spanning tree of a graph restricted to edges joining a men-majority school and a women-majority school, or report -1.
- Level
Medium5 of 10
- Topics
- Graph, Minimum spanning tree, Union-find, Greedy
- Solved
- No attempts yet
Problem
Kkaengmi is 24 and has never been in a relationship. Refusing to become a great wizard, Kkaengmi decides to use programming skills to build a group-dating app. The app targets university students and is built from data on the roads between universities.
The app offers its users a crush route. A crush route satisfies these three conditions:
- To satisfy the users' crushes, it consists only of roads that connect a men-majority university with a women-majority university.
- So that users can meet many different people, it lets them travel from any university to every other university.
- So that nobody wastes time, the total length of the roads in the route is as small as possible.
For example, if the road data looks like the figure on the left, building the route like the purple lines in the figure on the right satisfies all three conditions.

Using the given road data, find the length of the crush route.
Input
The first line contains the number of schools and the number of roads . (, )
The second line contains space-separated characters. The -th character is M if school is a men-majority university and W if it is a women-majority university.
Each of the next lines contains three integers , , and , meaning that school and school are connected by a road of length . (, )
Output
Print the length of the crush route of Kkaengmi's app. If the allowed roads cannot connect all schools, print -1.