AC Automaton
Time limit13sMemory limit1024 MB
Tree nodes are A, C, or ?. After each point update, find the most ancestor-descendant pairs with an A above a C, filling each ? freely.
- Level
Hard8 of 10
- Topics
- Tree, Segment tree, Dynamic programming
- Solved
- No attempts yet
Problem
JB is trying to get more "AC" on problems with his AC Automaton.
The AC Automaton is a rooted tree with nodes and node 1 as root. Each node except the root has its unique parent and a character on it, which is one of 'A', 'C', or '?'. A node is called an ancestor of if and only if or is an ancestor of . The number of "AC" JB can get is equal to the number of ordered pairs such that is an ancestor of , is 'A', and is 'C'. JB can replace each '?' with 'A' or 'C'. His goal is to get more "AC" after replacing all '?'.
However, the problem keeps changing. JB will change his AC Automaton times. Each time, he modifies the character on one node to 'A', 'C', or '?' (the character may stay the same). After each modification, find the maximum number of "AC" he can get if he replaces all '?' characters. JB does not actually modify the AC Automaton while calculating this maximum. See the sample for an example.
Input
The first line contains two integers and ().
The second line contains a string of characters, representing the character on each node. Every character is one of 'A', 'C', and '?'.
The third line contains integers. The -th integer () is the parent of node .
The next lines describe the modifications. The -th of these lines contains an integer () and a character ( is one of 'A', 'C', '?'), meaning node is set to .
Output
Output lines. The -th line contains one integer, the maximum number of "AC" after the -th modification.
Hint
After the first modification, one of the best ways to replace the characters is "ACCCC", and it has 4 pairs: (1,2), (1,3), (1,4), and (1,5).
After the second modification, one of the best ways to replace the characters is "ACCAC", and it has 3 pairs: (1,2), (1,3), and (1,5).
After the third modification, one of the best ways to replace the characters is "AACAC", and it has 3 pairs: (1,3), (2,3), and (1,5).