Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หา Good Permutation ของ N จำนวนธรรมชาติแรกใน C++

ในปัญหานี้ เราได้รับ N งานคือหา Good Permutation ของ 1..N

Good Permutation Definition

Permutation P ที่สำหรับทุก i (1 ≤ i ≤ N):

  • P[i] ≠ i (ไม่มี fixed point = Derangement)
  • P[P[i]] = i (เป็น Involution: swap แบบคู่)

เงื่อนไขและวิธีสร้าง

  • ถ้า N คี่ → ไม่มีคำตอบ (Output: -1)
  • ถ้า N คู่ → สลับคู่ๆ: (2,1), (4,3), (6,5), ...

ตัวอย่าง

Input: N = 4 Output: 2 1 4 3

P[1]=2, P[2]=1, P[3]=4, P[4]=3 → P[P[1]]=P[2]=1 ✓

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

void printGoodPermutation(int n) {
    if (n % 2 != 0) { cout << -1; return; }
    for (int i = 1; i <= n / 2; i++)
        cout << (2*i) << " " << (2*i - 1) << " ";
}

int main() {
    printGoodPermutation(4); // 2 1 4 3
    return 0;
}

ผลลัพธ์

Good Permutation of first N natural Numbers: 2 1 4 3