Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Two elements can only collide if they share the same remainder modulo K|K|, so we handle each remainder class independently. We are motivated to do so, since adding KK to each element doesn't change its remainder when divided by KK. In particular, we have

ai+kai(modk)a_i + k \equiv a_i \pmod{k}

and so we can consider the elements by their respective remainder.

Within each class, sort the elements in the direction of KK (ascending if K>0K > 0, descending if K<0K < 0). Then, iterate in sorted order, advancing each element only as much as strictly needed to make it distinct from the previous one. This greedy approach is optimal, since we never move an element more than necessary.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!