【codevs 1282】约瑟夫问题

来源:互联网 发布:九极会员登录软件 编辑:程序博客网 时间:2024/05/24 05:49

1282 约瑟夫问题
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 大师 Master
题解
题目描述 Description
有编号从1到N的N个小朋友在玩一种出圈的游戏。开始时N个小朋友围成一圈,编号为I+1的小朋友站在编号为I小朋友左边。编号为1的小朋友站在编号为N的小朋友左边。首先编号为1的小朋友开始报数,接着站在左边的小朋友顺序报数,直到数到某个数字M时就出圈。直到只剩下1个小朋友,则游戏完毕。

现在给定N,M,求N个小朋友的出圈顺序。

输入描述 Input Description
唯一的一行包含两个整数N,M。(1<=N,M<=30000)

输出描述 Output Description
唯一的一行包含N个整数,每两个整数中间用空格隔开,第I个整数表示第I个出圈的小朋友的编号。

样例输入 Sample Input
5 3

样例输出 Sample Output
3 1 5 2 4

数据范围及提示 Data Size & Hint

1.模拟
2.线段树
3.公式法//和模拟差不多,,

#include <iostream> #include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 300005;int n,m,cnt = 1;int num[MAXN];int main(){    scanf("%d %d",&n,&m);    for(int i = 1; i <= n; i ++)        num[i] = i;    while(n)    {        int cntt = (cnt + m - 1) % n;        if(cntt == 0)   cntt = n;        printf("%d ",num[cntt]);        for(int i = cntt; i < n; i ++)            num[i] = num[i + 1];        cnt = cntt;        n --;    }    return 0;}
1 0
原创粉丝点击