【题目来源】
https://www.acwing.com/problem/content/3562/
【题目描述】
N 个人围成一圈顺序编号,从 1 号开始按 1、2、3 顺序报数,报 3 者退出圈外,其余的人再从 1、2、3 开始报数,报 3 的人再退出圈外,依次类推。
请按退出顺序输出每个退出人的原序号。
要求使用环形链表编程。
【输入格式】
第一行包含整数 T,表示共有 T 组测试数据。
每组数据一行,一个整数 N。
【输出格式】
每组数据输出一行,一个结果,包含每个退出人的原序号,用空格隔开。
【数据范围】
1≤T≤5,
1≤N≤50
【输入样例】
1
4
【输出样例】
3 2 4 1
【算法分析】
初始化标记数组 st[] 为0,表示人均未出圈。
若第 i 个人出列,则标记 st[i] 为 1,表示该人已出圈,不再进行报数。
同时,定义一个计数器 cnt,用于统计出圈的人数。注意:判断条件是 cnt<n,而不是 cnt<=n。
【算法代码】
#include<bits/stdc++.h>
using namespace std;
const int maxn=55;
int st[maxn];
int main() {
int T;
cin>>T;
while(T--) {
int cnt=0; //Number of people leaving the circle
int idx=0,sum=0;
memset(st,0,sizeof st);
int n;
cin>>n;
while(cnt<n) { //not cnt<=n
idx++;
if(idx>n) idx=1;
if(st[idx]==0) {
sum++;
if(sum==3) {
cnt++;
st[idx]=1;
cout<<idx<<" ";
sum=0;
}
}
}
cout<<endl;
}
return 0;
}
/*
in:
5
1
2
3
4
5
out:
1
1 2
3 1 2
3 2 4 1
3 1 5 2 4
*/
【参考文献】
https://www.acwing.com/solution/content/126712/
https://blog.csdn.net/hnjzsyjyj/article/details/142288659
https://blog.csdn.net/hnjzsyjyj/article/details/142285392