Explanation
Two elements can only collide if they share the same remainder modulo , so we handle each remainder class independently. We are motivated to do so, since adding to each element doesn't change its remainder when divided by . In particular, we have
and so we can consider the elements by their respective remainder.
Within each class, sort the elements in the direction of (ascending if , descending if ). 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:
#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!