在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP