題目:2n 張牌初始順序 1,2,…,2n。一次洗牌將前 n 張插入偶數位置(2,4,…,2n),後 n 張插入奇數位置(1,3,…,2n-1)。求回到初始順序所需洗牌次數。
orig[2n] 與工作陣列 cur[2n]。cur 前半段放入暫存 first[],後半段放入 second[];重組 cur 為 second[0], first[0], second[1], first[1]…。cur 與 orig,相同則停止,輸出計數。#include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int *orig = new int[2*n], *cur = new int[2*n];
for (int i = 0; i < 2*n; i++) orig[i] = cur[i] = i;
int *first = new int[n], *second = new int[n];
int count = 0;
bool same = false;
while (!same)
{
for (int i = 0; i < n; i++) first[i] = cur[i];
for (int i = 0; i < n; i++) second[i] = cur[n+i];
for (int i = 0; i < 2*n; i++)
cur[i] = (i % 2 == 0) ? second[i/2] : first[i/2];
count++;
same = true;
for (int i = 0; i < 2*n; i++)
if (cur[i] != orig[i]) { same = false; break; }
}
cout << count << " 次後還原。";
return 0;
}
輸入 10 → 輸出 6。純陣列操作,無需鏈結串列,適合演算法競賽與教學示範。