>  기사  >  백엔드 개발  >  인접한 요소 간의 절대 차이가 1보다 크도록 처음 N개의 자연수를 배열합니다.

인접한 요소 간의 절대 차이가 1보다 크도록 처음 N개의 자연수를 배열합니다.

PHPz
PHPz앞으로
2023-09-07 22:01:021048검색

인접한 요소 간의 절대 차이가 1보다 크도록 처음 N개의 자연수를 배열합니다.

첫 번째 N개의 자연수가 있습니다. 우리의 임무는 두 개의 연속 요소 사이의 절대 차이가 1보다 큰 순열을 얻는 것입니다. 그러한 배열이 없으면 -1이 반환됩니다.

방법은 매우 간단합니다. 탐욕스러운 방법을 사용하겠습니다. 모든 홀수를 오름차순 또는 내림차순으로 정렬한 다음 모든 짝수를 내림차순 또는 오름차순으로 정렬합니다.

Algorithm

arrangeN(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

Example

중국어 번역:

Example

#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);
}

Output

으으으으

위 내용은 인접한 요소 간의 절대 차이가 1보다 크도록 처음 N개의 자연수를 배열합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제