처음 N개의 자연수가 있습니다. 우리의 임무는 모든 두 연속 요소 간의 절대 차이가> 1인 경우 하나의 순열을 얻는 것입니다. 이러한 순열이 없으면 -1을 반환합니다.
접근 방식은 간단합니다. 우리는 탐욕스러운 접근 방식을 사용할 것입니다. 모든 홀수를 오름차순 또는 내림차순으로 정렬한 다음 모든 짝수를 내림차순 또는 오름차순으로 정렬합니다.
알고리즘
배열N(n)
Begin if N is 1, then return 1 if N is 2 or 3, then return -1 as no such permutation is not present even_max and odd_max is set as max even and odd number less or equal to n arrange all odd numbers in descending order arrange all even numbers in descending order End
예시
#include <iostream>
using namespace std;
void arrangeN(int N) {
if (N == 1) { //if N is 1, only that will be placed
cout << "1";
return;
}
if (N == 2 || N == 3) { //for N = 2 and 3, no such permutation is available
cout << "-1";
return;
}
int even_max = -1, odd_max = -1;
//find max even and odd which are less than or equal to N
if (N % 2 == 0) {
even_max = N;
odd_max = N - 1;
} else {
odd_max = N;
even_max = N - 1;
}
while (odd_max >= 1) { //print all odd numbers in decreasing order
cout << odd_max << " ";
odd_max -= 2;
}
while (even_max >= 2) { //print all even numbers in decreasing order
cout << even_max << " ";
even_max -= 2;
}
}
int main() {
int N = 8;
arrangeN(N);
} 출력
7 5 3 1 8 6 4 2