Codeforces Round 993 (Div. 4) -- My Editorial
You can run a brute force code iterating for $1$ to $n$ as $a$ and $b$ yield $\mathcal{O}(n^2)$ , however
it can be shown that the answer can be shortcuted to just $n-1$ in $\mathcal{O}(1)$.
For each character $\mathtt{p}$ or $\mathtt{q}$ , just alternate between them , and finally
reverse the string , $\mathcal{O}(n)$.
This is a simulation problem , The monkeys will set in first row are $x=\min(a,m)$ , in second row as well
$y=\min(b,m)$ , now remains the monkeys with no preferances $z=\min(2m-x-y,c)$ , The final answer is $x+y+z$.
Complexity is $\mathcal{O}(1)$.
The Key to solve the problem to Notice that $\textbf{There can be serveral modes for the array}$ thus
we can use all elements in range $[1,n]$ in such that works , this can be done , by maintaining an array
$done$ that tracks if we added some integer $x$ in new array $b$ , so according to $a$ we keep add non-added elements
and the rest of numbers is complement of numbers in range $[1,n]$ that doesn't appear in $a$ , thus the array $b$
satisfies the conditions and our solution is complete , Complexity $\mathcal{O}(n)$.