2037:【例5.4】约瑟夫问题

错误原因:

因为没有找好循环规律,出局人的索引

思路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++; // 出圈的人数加一 
		}
	} 
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值