The problem:
Put the numbers from 1 to M into M columns. At the beginning column i contains only number i. Then, perform N queries of two possible types:
- A i j: remove all numbers from column i and put them (in the same order) at the end of column j
- B i j: if the numbers i and j are not in same column, print -1; otherwise, print the number of elements strictly between them.
The constrains are N <= 200,000 and M <= 30,000
My approach:
I though of using a union-find structure to solve the problem. The issue is that a union-find doesn't remember the order of the elements of the sets that it builds, therefore I would not be able to fully answer queries of type B.
Could you give the solution or at least some hints to guide in the right direction ?