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.
For position , the easiest number divisible by is just itself. Try to make for every .
So the task becomes: can you arrange so that consecutive absolute differences are in that exact order?
It is easier to first build the reverse: a permutation whose consecutive differences are .
Alternating small and large values does exactly that: .
Build , then reverse it. In the reversed array, the difference at position becomes exactly , so the condition is automatically satisfied.
The condition says must be divisible by . Instead of trying to use random multiples of , use the most boring valid multiple: itself. If we can construct a permutation with
for every , then the divisibility condition is done. No drama.
Now build a helper permutation whose consecutive differences go the other way:
There is a very simple construction:
That means we repeatedly take the smallest unused number, then the largest unused number.
Why does this work? Look at adjacent terms:
More formally, for every adjacent pair in at position ,
So the differences of are exactly
But we need the differences to be in that order. So just reverse and call the result .
If
then the difference between and corresponds to the difference between and , which is exactly :
Since is divisible by , every condition holds.
The array is definitely a permutation because the construction uses every number from to exactly once: one from the left end, one from the right end, until nothing is left.
Edge cases are harmless. For , the construction gives either after reversing, and the only required difference is , which works. Odd just leaves one middle number at the end of the helper array before reversing; still fine.
Complexity per test case is time and memory. With , this is basically free, but still clean.
#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;
vector<int> a;
int l = 1, r = n;
while (l <= r) {
a.push_back(l++);
if (l <= r) a.push_back(r--);
}
reverse(a.begin(), a.end());
for (int i = 0; i < n; i++) {
if (i) cout << ' ';
cout << a[i];
}
cout << '\n';
}
}#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;
vector<int> a;
int l = 1, r = n;
while (l <= r) {
a.push_back(l++);
if (l <= r) a.push_back(r--);
}
reverse(a.begin(), a.end());
for (int i = 0; i < n; i++) {
if (i) cout << ' ';
cout << a[i];
}
cout << '\n';
}
}