PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: notsoloud
Tester: yash_daga
Editorialist: iceknight1093
DIFFICULTY:
1196
PREREQUISITES:
Familiarity with bitwise OR
PROBLEM:
Given N, find a permutation P of \{1, 2, 3, \ldots, N\} such that for each i \geq 3, P_i \neq P_{i-1} \mid P_{i-2}.
\mid denotes bitwise OR.
EXPLANATION:
For any two integers x and y, note that (x\mid y) \geq x (and so (x\mid y) \geq y as well).
In particular, if we want an integer z such that z \neq (x\mid y), the easiest way is to just ensure that z \lt x and z \lt y: this way, nothing else needs to be checked!
In context of our task, that just means if we’re able to ensure that P_i is strictly less than both P_{i-1} and P_{i-2}, the condition will be satisfied.
That’s pretty easy to do: arrange everything in descending order!
That is, one valid solution is to just print [N, N-1, N-2, \ldots, 3, 2, 1].
TIME COMPLEXITY:
\mathcal{O}(N) per testcase.
CODE:
Author's code (C++)
#include <iostream>
using namespace std;
int main() {
int t = 0;
cin >> t;
while(t--){
int n;
cin >> n;
for(int i = n; i>=1; i--) cout << i <<' ';
cout << endl;
}
return 0;
}
Editorialist's code (Python)
for _ in range(int(input())):
n = int(input())
print(*reversed(list(range(1, n+1))))