Search for a command to run...
Progressive hints first, then the full explanation and implementation when you're ready to cash out.
Review status
AI-generated and still unreviewed. Double-check the details before internalizing them.
Hints
Open only as much as you need to keep the solve alive.
Don’t try to control every adjacent pair separately. That’s how you end up fighting the condition one tiny GCD at a time, which is miserable.
The condition only looks at the values . So think about designing those sums first, then making fit afterward.
If every sum were the same number , then every adjacent GCD would be .
Can you choose a constant so that is always an integer from to , with no repeats?
Use . Then set . Since is a permutation, this produces every number from to exactly once, and all sums equal .
The trick is to stop overthinking the GCD condition.
We need a permutation such that for every adjacent pair:
At first glance, this looks like we need to carefully arrange so each neighboring pair has some common factor. That sounds annoying. Luckily, there is a much cleaner way: make all the sums equal.
Key Idea
If we can force
for every position , then every adjacent pair becomes:
So we just need .
Now the question becomes: can we choose so that every equals the same constant?
Yes. Use:
Then:
So every sum is exactly .
Since , we have:
Therefore:
Condition nuked. Done.
Why is a valid permutation?
Because contains every number from to exactly once.
The transformation
also maps the set to itself:
No duplicates appear, and no value goes outside the range. So is also a permutation of size .
Algorithm
For each test case:
That’s it. This problem is basically asking for the complement permutation, wearing a fake mustache labeled “number theory.”
Complexity
For each test case, we process the permutation once.
time per test case, and
extra memory besides the input/output.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int p;
cin >> p;
cout << n + 1 - p << (i + 1 == n ? '\n' : ' ');
}
}
return 0;
}#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
}
int main() {
setIO();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int p;
cin >> p;
cout << n + 1 - p << (i + 1 == n ? '\n' : ' ');
}
}
return 0;
}