### PROBLEM LINK:

**Author:** Praveen Dhinwa

**Tester:** Mugurel Ionut Andreica

**Editorialist:** Kirill Gulin

# PROBLEM

You’re given an array a of size N, each number in the array appears no more than twice. Shuffle the array in such a way that the Hamming distance between the original and the shuffled array is maximized. The Hamming distance between two arrays a and b is the number of indexes i such that a_i eq b_i.

### QUICK EXPLANATION

Count how many numbers in the array have their frequences equal to 1 or 2. Solve the problem depending on are these numbers more than 1.

### EXPLANATION

## Subtask 1

All elements in the array are unique. Just cyclically shift the array. So for the first substask the answer is 0 if N = 1 and N if N \geq 2.

## Subtask 2

If you pass only the second subtask it means you missed some corner cases while solving the 3rd subtask.

##Subtask 3

For each number existing in the array count its frequence. Suppose there are x numbers with their frequence equal to 1 and y numbers with frequence equal to 2.

Suppose x, y \geq 2. We can separately shuffle the numbers with frequence 1 and with frequence 2, getting the answer equal to N for this case. Shuffling here and below means you’ll need to write out indexes of number’s entries and set the other number on its entries (for example, cyclically shift the array of indexes by 1). For example, if the array is [a, b, c, d, d, c] you’ll get an array [b, a, d, c, c, d] after such a shuffle.

There are two ways of solving the problem now: random shuffle and dealing with corner cases.

### The first way

Random shuffle the array several times and choose the one with the maximum Hamming distance. The answer you’ve got is correct with high enough probability.

### The second way

Suppose x = 1 and y \geq 2. Then shuffle only the numbers with frequence 2 and swap the number with frequence 1 with any other number.

Suppose x \geq 2 and y = 1. Then shuffle only the numbers with frequence 1 and swap the indexes of the number with frequence 2 with any two other different indexes.

After these cases, N \leq 4 so you can try all possible shuffles of the array in O(N!) time. But still sorting out the cases is possible

If x = 2, y = 0 then N = 2. Just swap the values.

Cases with x = 0, y = 2 or x = y = 1 or x = 1, y = 0 or x = 0, y = 1 are left. For any of them you can cyclically shift the array twice. Calculate the Hamming distance and print the answer.

### AUTHOR’S AND TESTER’S SOLUTIONS:

Author’s solution can be found here.

Tester’s solution can be found here.