PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#DSU0000075. Những chuyến đi của đàn bò (COW Traversals)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Những chuyến đi của đàn bò (COW Traversals)

COW Traversals

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

There are NN cows, with cow ii living in barn ii and having best friend aia_i, possibly itself. Over MM nights, on night jj, cow cjc_j begins hosting a party of type tj∈{C,O,W}t_j\in\{\texttt{C},\texttt{O},\texttt{W}\}. If it was already hosting a party, that type is replaced; all other parties continue.

Every cow checks its own barn for a party. If none exists, it visits the best friend's barn, repeating the process. A cow that enters a cycle without finding a party gives up. For each night, count the cows attending parties of types C, O, and W.

Every night, all cows start at their own barns rather than continuing from where they stopped the previous night. A cow joins the first party encountered on its route and stops moving. If it follows a cycle without encountering a party, it attends no party that night.

A party created on night jj takes effect that night and remains active on subsequent nights until its own barn changes the party type. Changing one barn's party does not cancel parties at other barns.

Input

The first line contains NN, the second contains a1,…,aNa_1,\ldots,a_N, followed by MM and then MM lines containing cj,tjc_j,t_j.

Output

Print MM lines, each with three integers: the numbers of cows attending party types C, O, and W, respectively.

Subtasks

  • Subtask 1 (20 points): 1≤N≤201\le N\le 20; 1≤M≤501\le M\le 50; 1≤ai,cj≤N1\le a_i,c_j\le N; tj∈{C,O,W}t_j\in\{\texttt{C},\texttt{O},\texttt{W}\}.
  • Subtask 2 (30 points): 1≤N≤40001\le N\le 4000; 1≤M≤40001\le M\le 4000; 1≤ai,cj≤N1\le a_i,c_j\le N; tj∈{C,O,W}t_j\in\{\texttt{C},\texttt{O},\texttt{W}\}.
  • Subtask 3 (50 points): 1≤N≤2000001\le N\le 200000; 1≤M≤2000001\le M\le 200000; 1≤ai,cj≤N1\le a_i,c_j\le N; tj∈{C,O,W}t_j\in\{\texttt{C},\texttt{O},\texttt{W}\}.

Examples

Input

5
2 3 4 5 4
4
2 C
4 C
4 W
2 O

Output

2 0 0
5 0 0
2 0 3
0 2 3

Explanation

On night 11, cows 1,21,2 reach the C party at barn 22. On night 22, barn 44 adds a C party attended by cows 3,4,53,4,5. On night 33, that party changes to W, giving 22 cows at C and 33 at W. On night 44, barn 22 changes its party to O, so the result is 0 2 30\ 2\ 3.