#5406. Problem 1. COW Traversals

0

Problem 1. COW Traversals

Problem 1. COW Traversals

USACO 2026 First Contest, Gold

There are NN (1N21051\le N\le 2\cdot 10^5) cows labeled 1N1\dots N on Farmer John's farm, where each cow lives in its own barn. Each cow ii has a best friend aia_i (1aiN1\le a_i\le N). Cows can be best friends with themselves, and multiple cows can have the same best friend. The cows love to party, so they have decided to throw a party for MM (1M21051\le M\le 2\cdot 10^5) consecutive nights.

On night ii, cow cic_i will decide to throw a party of type tit_i at its barn, where ti"COW"t_i\in \texttt{"COW"}. This party will exist for all future nights as well, until cow cic_i decides to throw a party of a different type.

Every night, each cow will attempt to go to a party. If a cow is not hosting a party, they will check their best friend's barn, and if there is no party there, will follow their best friend to wherever they are going (who might also follow their best friend and so on). It is possible that a cow might never find a party and will then give up for the night.

Compute for each night, the number of cows that end up at a party of type CC, OO, and WW respectively.

INPUT FORMAT (input arrives from the terminal / stdin):

The first line contains NN, the number of cows.

The second line contains a1,,aNa_1,\dots, a_N, where aia_i is cow ii's best friend.

The third line contains MM, the number of nights.

The next MM lines each contain an integer cic_i (1ciN1\le c_i\le N) and a character viv_i, representing the cow that is throwing the party and the party type respectively.

OUTPUT FORMAT (print output to the terminal / stdout):

Output MM lines, where the iith consists of 33 space-separated integers, the number of cows going to parties of type CC, OO, and WW on the iith night, respectively.

SAMPLE INPUT:


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

SAMPLE OUTPUT:


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

On night 11, there is only one party of type CC at barn 22, which only cows 11 and 22 attend.

On night 22, there is a new party of type CC at barn 44, which cows 33, 44, and 55 can now reach.

On night 33, the party at barn 44 is changed to type WW, affecting cows 33, 44 and 55.

On night 44, the party at barn 22 is changed to type OO, affecting cows 11 and 22.

SCORING: Input 2: N,M100N, M\leq 100Inputs 3-4: N,M4000N, M\leq 4000Inputs 5-9: {ai}\{a_i\} is a permutation of {1,,N}\{1,\dots, N\}Inputs 10-21: No additional constraints

Problem credits: Benjamin Qi