题解 | #约瑟夫环#
约瑟夫环
https://ac.nowcoder.com/acm/problem/22227
思路:
1、循环找到未出队且报数为m的人;
2、置0(表淘汰);
3、找到还在队内的下一个人,开始新的循环(报数);
4、当队内还剩1个人时跳出循环,此时报数的人即为大王
#include <bits/stdc++.h>
using namespace std;
int ar[100];
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n,k,m,tmp,tmp_m;
cin>>n>>k>>m;
for(int i = 0;i < n;i++)
ar[i] = 1;
tmp = n;
while(tmp != 1){
tmp_m = m;
while(1){ //找出报到m号的人
if(ar[k]){
tmp_m--;
if(!tmp_m) break;
}
k = (k+1)%n;
}
ar[k] = 0; //k号出队
while(1){ //找到下一个报数起点
k = (k+1)%n;
if(ar[k]) break;
}
tmp--;
}
cout<<k;
return 0;
}