题目链接:http://acm.swjtu.edu.cn/JudgeOnline/showproblem?problem_id=2213
思路分析:该问题与约瑟夫问题相似;每次将前n张牌放到队列的最后,可以将整个队列看做一个环,每次向前移动n步,则下一张牌的号码即被编号为n,
并在该环中除去该牌,在继续前行n+1步,如此循环,直到最后一张牌被编号。
代码如下:
#include <iostream> using namespace std; const int MAX_N = 20; int del[MAX_N]; int num[MAX_N]; int main() { int times; cin >> times; while (times--) { int n = 0; int index = -1; memset(del, 0, sizeof(del)); memset(num, -1, sizeof(num));
cin >> n; for (int i = 0; i < n; ++ i) { int times = i + 1; int go = times; while (go) { index = (index + 1) % n; if (del[index] != 1) go--; } index = (index + 1) % n; while (del[index] == 1) index = (index + 1) % n; num[index] = times; del[index] = 1; } for (int i = 0; i < n - 1; ++i) cout << num[i] << " "; cout << num[n - 1] << endl; } return 0; }
时间: 2024-10-07 10:51:59