10424 - 约瑟夫问题

题目:

有N个人,编号分别为1~N,按顺序排成一个圈。

现在给定一个数M,从第一个人开始依次报数,数到M的人出圈;然后下一个人又从1开始报数,数到M的人又出圈……如此循环,直到最后一个人出圈为止。

输入

包括2个整数N,M(1 ≤ N,M ≤ 32767)。

输出

N个人的出圈顺序

样例

输入

9 6

输出

6
3
1
9
2
5
4
8
7

这道题有很多方法,比如数组、链表等

因为时间原因,就只给2种方案了

答案1:链表

#include<bits/stdc++.h>
using namespace std;

struct nod
{
    int nxt,pre;
}List[1005];

int cnt;

void Delete(int p)
{
    List[List[p].pre].nxt=List[p].nxt;
    List[List[p].nxt].pre=List[p].pre;
}

int main()
{
    int N,M,s = 0;
    cin >> N >> M;
    int NP = N;
    for(int i = 1 ; i <= N ; i++)
        List[i].pre = i - 1,List[i].nxt = i + 1;
    List[1].pre = N;List[N].nxt = 1;
    int f = 1;
    for(int i = 1 ; NP >= 1 ; i++)
    {
        s++;
        if (s == M)
        {
            s = 0;
            cout << f << ' ';
            Delete(f);
            NP--;
        }
        f = List[f].nxt;
    }
    return 0;
}

答案2:数组

#include<bits/stdc++.h>

using namespace std; int main() {

int a , b , x = 0;
cin >> a >> b;
int c[a + 1];
for(int i = 1;i <= a;i++)
{
	c[i] = i;
}
for(int i = 0;i < a;i++)
{
	for(int j = 0;j < b;j++)
	{
		x++;
		if(x == a + 1)
		{
			x = 1;
		}
		while(c[x] == -1)
	    {
		    x++;
		    if(x == a + 1)
		    {
			    x = 1;
		    }
	    }
	}
	
    cout << c[x] << endl;
    c[x] = -1;
}
return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值