在C++中查詢2N個數的排列,使得給定表示式的結果恰好為2K


假設我們有兩個整數N和K。我們必須找到前2N個自然數的第一個排列,使得滿足以下等式。

$$ \displaystyle\sum\limits_{i=1}^N |A_{2i-1}-A_{2i}| + | \displaystyle\sum\limits_{i=1}^N A_{2i-1}-A_{2i} | = 2K $$

K的值應該小於或等於N。例如,如果N = 4且K = 1,則輸出將為2 1 3 4。給定表示式的結果將為(|2 – 1| + |3 – 4|) – (|2 – 1 + 3 – 4|) = 2。

這個想法很簡單,假設我們有一個排序的序列,例如1, 2, 3, 4, 5, 6, …。如果我們交換任何兩個索引2i – 1和2i,結果將恰好增加2。我們需要進行K次這樣的交換。

示例

線上演示

#include<iostream>
using namespace std;
void showPermutations(int n, int k) {
   for (int i = 1; i <= n; i++) {
      int a = 2 * i - 1;
      int b = 2 * i;
      if (i <= k)
         cout << b << " " << a << " ";
      else
         cout << a << " " << b << " ";
   }
}
int main() {
   int n = 4, k = 2;
   showPermutations(n, k);
}

輸出

2 1 4 3 5 6 7 8

更新於:2019年12月18日

63 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告