2

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:

  1. A i j: remove all numbers from column i and put them (in the same order) at the end of column j
  2. 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 ?

Benny
  • 41
  • 4
  • Is it important that the numbers actually be moved as described, or just that you're able to answer queries of type 2 as if the numbers had been moved? – Dave May 06 '22 at 01:55
  • You just need to be able to answer query of type (2), according to the changes made by queries of type (1). – Benny May 07 '22 at 21:45

1 Answers1

2

You can use a union-find data structure if you keep track of the size of each root set (just use union-by-size instead of union-by-rank), and add an additional delta field to each node, such that:

  • In set roots, delta gives the position the root element in the list of the set's elements; and
  • In other nodes, delta gives the difference between the element's position and its parent's position.

This makes it easy to find the position of elements during "find" operations, which you can use to answer type (2) queries.

Type (1) queries would be implemented by union. The additional delta fields are easy to update in both set-union and path compression operations.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • This seems like the right answer, although the implementation of the delta field may be easy to get wrong. Also, it seems like you'd need an associative array/similar structure on top to determine which set root is in which column for Type (1) queries – kcsquared May 06 '22 at 16:49
  • You don't need any extra data structure. For type 1 queries, it's easy to check if a column is non-empty -- if so, then its element is at position 0 in its list. – Matt Timmermans May 06 '22 at 16:55