错误原因:
因为没有找好循环规律,出局人的索引
思路1:
创建一个数组,存编号,如果出局则从数组里删去此人,直到数组里没有人时,结束循环
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 10001;
int a[maxn];
int main(){
int n,m,cnt = 0; cin >> n >> m;
for(int i = 0; i <= n; i++) a[i] = i+1; //创建一个数组,来存编号
while(n){ // 当圈内人数为0时终止循环
cnt = (cnt + m-1) %n; //计算出局人的索引
cout << a[cnt] << " "; //输出出局人的编号
for(int j = cnt; j <= n; j++){
a[j] = a[j+1];
} //从数组里删去出局的人
n--; //总人数-1;
}
}
思路2:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 10001;
int a[maxn] = {0};
int main(){
int n,m;
cin >> n >> m;
int f = 0,t = 0,s=0;
while(f < n){
t++;
if(t == n+1) t=1; // 组成一个环形
if(a[t] == 0) s++; // 未出圈则要报数
if(s == m){
s = 0; // 从新报数
cout << t << " "; //输出出圈的人的编号
a[t] = 1; //标记出出圈的人
f++; // 出圈的人数加一
}
}
}