Repovive
  • Dashboard
  • Ranking
  • Submissions
  • Discussion
  1. Contests
  2. Premier Round 9
  3. 27G

My submissions

/
/
/
/

Announcements

My submissions

/
/
/
/

Announcements

Solve
Author

27G. Soap Warehouse

3500 pts·4s·512 MB

Constraints

Input

Output

Samples

Input
t
2
Case 1
2
FF
1 2 5
Case 2
4
HHHF
1 2 1
2 3 1
3 4 1
Explanation
Case 1
Case 2

There are two face turns, but only one bar of face soap, so collecting all the soap is impossible.

Output
Case 1
10
Case 2
-1
Input
t
3
Case 1
4
FHHF
1 2 1
2 3 1
3 4 1
Case 2
6
HHHFFF
1 2 1
2 3 1
3 4 1
4 5 1
5 6 1
Case 3
6
HHFFFF
1 2 1
2 3 1
3 4 1
4 5 1
5 6 1
Explanation
Case 1
Case 2
Case 3
Output
Case 1
6
Case 2
18
Case 3
12

A warehouse contains nnn rooms connected by corridors that form a tree. Each corridor has a length. Room iii contains one bar of soap described by sis_isi​: hand soap (H) or face soap (F).

You start in room 111. Collect every bar of soap exactly once and finish in room 111. You may visit rooms and traverse corridors any number of times; visiting a room does not force you to collect its soap.

The required types of collected soap alternate as hand, face, hand, face, and so on. On a hand turn, you may collect either type of soap. On a face turn, you may collect only face soap.

Find the minimum possible total length of all traversed corridors. If it is impossible to collect all bars under these rules, output −1-1−1.

  • 1≤t≤1041 \le t \le 10^41≤t≤104
  • 2≤n≤2×1052 \le n \le 2 \times 10^52≤n≤2×105
  • nnn is even.
  • The sum of nnn over all test cases does not exceed 2×1052 \times 10^52×105.
  • sss is a string of length nnn consisting only of H and F.
  • 1≤ui,vi≤n1 \le u_i, v_i \le n1≤ui​,vi​≤n
  • 1≤wi≤1061 \le w_i \le 10^61≤wi​≤106
  • The n−1n-1n−1 corridors form a tree.
ttt ns1s2…snu1v1w1u2v2w2⋮un−1vn−1wn−1}×t\left. \begin{array}{l} n \\ s_1s_2\ldots s_n \\ u_1\quad v_1\quad w_1 \\ u_2\quad v_2\quad w_2 \\ \vdots \\ u_{n-1}\quad v_{n-1}\quad w_{n-1} \end{array} \right\} \times tns1​s2​…sn​u1​v1​w1​u2​v2​w2​⋮un−1​vn−1​wn−1​​⎭⎬⎫​×t
answer  }×t\mathrm{answer}\;\} \times tanswer}×t

Collect the soap in room 111 on a hand turn and the soap in room 222 on a face turn, then return. The corridor is traversed twice, for a total distance of 101010.

Collect the soaps in rooms 2,4,3,12,4,3,12,4,3,1, in that order. Pass through room 333 on the way to room 444 without collecting its soap yet. The total distance is 666.

Collect the soaps in rooms 1,4,2,5,3,61,4,2,5,3,61,4,2,5,3,6, in that order, then return to room 111. The total distance is 181818.

Collect the soaps in rooms 1,3,2,4,5,61,3,2,4,5,61,3,2,4,5,6, in that order, then return to room 111. The face soap in room 555 fills a hand turn. The total distance is 121212.