Under construction

Still being built. Things may change

Love That Only Fails for Me

Time limit2sMemory limit256 MB

Summary
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:

  1. To satisfy the users' crushes, it consists only of roads that connect a men-majority university with a women-majority university.
  2. So that users can meet many different people, it lets them travel from any university to every other university.
  3. 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 NN and the number of roads MM. (2≤N≤1 0002 \le N \le 1\,000, 1≤M≤10 0001 \le M \le 10\,000)

The second line contains NN space-separated characters. The ii-th character is M if school ii is a men-majority university and W if it is a women-majority university.

Each of the next MM lines contains three integers uu, vv, and dd, meaning that school uu and school vv are connected by a road of length dd. (1≤u,v≤N1 \le u, v \le N, 1≤d≤1 0001 \le d \le 1\,000)

Output

Print the length of the crush route of Kkaengmi's app. If the allowed roads cannot connect all schools, print -1.

Examples1

  1. Example 1

    Input
    5 7
    M W W W M
    1 2 12
    1 3 10
    4 2 5
    5 2 5
    2 5 10
    3 4 3
    5 4 7
    
    Expected output
    34