Marin and Anti-coprime Permutation codeforces solution in c++
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
if (n == 1) {
cout << "1\n";
return 0;
}
if (n <= 3) {
cout << "NO SOLUTION\n";
return 0;
}
vector<int> permutation;
for (int i = 2; i <= n; i += 2) {
permutation.push_back(i);
}
for (int i = 1; i <= n; i += 2) {
permutation.push_back(i);
}
for (int i = 0; i < n; i++) {
cout << permutation[i] << " ";
}
cout << "\n";
return 0;
}
Explanation:
Include Libraries: The code starts by including the necessary libraries -
iostream
for input/output operations andvector
to use a dynamic array.Main Function: The program's execution starts from the
main()
function.Input: It reads an integer
n
from the standard input (keyboard).Special Cases Handling:
- If
n
is 1, the program outputs "1" and terminates. - If
n
is less than or equal to 3, there is no solution, so it outputs "NO SOLUTION" and terminates.
- If
Permutation Generation:
- For
n
greater than 3, it initializes an empty vectorpermutation
to store the permutation. - Two loops are used:
- The first loop (
for (int i = 2; i <= n; i += 2)
) adds even numbers starting from 2 ton
to the permutation vector. - The second loop (
for (int i = 1; i <= n; i += 2)
) adds odd numbers starting from 1 ton
to the permutation vector.
- The first loop (
- For
Output:
- Finally, it prints the generated permutation stored in the
permutation
vector.
- Finally, it prints the generated permutation stored in the
This code generates a permutation of numbers from 1 to n
such that for any number x
in the permutation, x
and x+1
are not coprime (do not have a greatest common divisor of 1).