首頁 > 後端開發 > C++ > 主體

安排前N個自然數,使得相鄰元素的絕對差大於1

PHPz
發布: 2023-09-07 22:01:02
轉載
1061 人瀏覽過

安排前N個自然數,使得相鄰元素的絕對差大於1

我們有前 N 個自然數。我們的任務是獲得它們的一種排列,其中每兩個連續元素之間的絕對差 > 1。如果不存在這樣的排列,則傳回 -1。

方法很簡單。我們將使用貪心方法。我們將所有奇數按升序或降序排列,然後將所有偶數按降序或升序排列

演算法

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

的中文翻譯為:

範例

#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
登入後複製

以上是安排前N個自然數,使得相鄰元素的絕對差大於1的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!