Maintain an array under swaps and union operations, answering whether it can be sorted and counting pairs of clouds whose merge would fix both.
Hard9Union-findImplementationMathSortingNo attempts yetTime limit6sMemory limit512 MBDominik has in mind an array of positive integers p1,…,pN. Write q1,…,qN for the same array sorted in non-decreasing order.
He also has in mind a set of allowed swaps. If the pair (X,Y) is in the set of allowed swaps, Dominik can swap the numbers at positions X and Y of the array p. The set of allowed swaps is empty at the start.
Marin gives Dominik Q queries. Each query is one of the following four kinds.
Swap the numbers at positions A and B.
Add the pair (A,B) to the set of allowed swaps. Marin can give a pair that is already in the set.
Decide whether the array can be sorted using only the allowed swaps. The swaps can be used in any order, and each swap can be used any number of times.
Two positions (A,B) are linked if the number at position A can be moved to position B using only allowed swaps. The set of all positions linked to position A is the cloud of A. A cloud is good if the allowed swaps can be applied so that pj=qj holds at the same time for every position j of that cloud.
Count the pairs of distinct positions (A,B) that satisfy all three conditions below.
The pairs (A,B) and (B,A) count as the same pair.
The first line contains the integers N and Q (1≤N,Q≤106).
The second line contains N integers p1,…,pN (1≤pi≤106).
Each of the next Q lines contains one query.
For each query of kind 3 or 4, print the answer on its own line.
The answer to a query of kind 3 is DA if the array can be sorted and NE if it cannot. These words are Croatian for yes and no, and they are printed without quotation marks.
The answer to a query of kind 4 is the non-negative integer defined in the statement.
In the first example p=[1,3,2] and q=[1,2,3]. No swap is allowed at the start, so every position forms a cloud that holds only itself.
The answer to the first query is 1, because (2,3) is the only pair that satisfies all three conditions.
The answer to the second query is NE, because the set of allowed swaps is empty and the numbers 2 and 3 cannot reach their places.
The third query adds the pair (2,3) to the set of allowed swaps.
The answer to the fourth query is 0, because positions 2 and 3 are already linked.
The answer to the fifth query is DA, because one application of the allowed swap (2,3) sorts the array.