[HNUOJ 10045] Joseph‘s Puzzle

该博客主要讨论了约瑟夫环问题的解决方法,通过编程实现了一个基于圈中人数N和计数因子M的算法,描述了在循环坐标的场景下,按照特定规则逐一淘汰直到所有人离开的过程。程序采用队列数据结构,不断更新计数并移除对应位置的人,输出了按照离开顺序的序列号。
摘要由CSDN通过智能技术生成
Joseph's Puzzle
Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB
Total submit users: 1140, Accepted users: 771
Problem 10045 : No special judgement
Problem description
Persons, whose number order is from 1 to N, hold a password (the straight integer less than 10000) each person and sit around clockwise.
At first we choose a positive integer factor as the count off number M and start to number clockwise from number one .As we number to M the person who numbers M leaves the rank and whose password will be the new number M. And then start to number again from the person who is sit clockwise next to the person who has been out off the rank just before then. Continue like this, until all people are out off the rank completely. Please design a program of leaving order.
 
Input
There have some groups data. First line of each group data is two integers N, M (0<N, M<100),the second line is N positive integer, separately express every person’s password.The last line contins 0,0 ,which means the end of input data.
 
Output
To each group of data, according to the order which leaves outputs their serial number. Between the numeral separates with a blank space. Each group of data monopolize line of outputs.
 
Sample Input
7 20
3 1 7 2 4 8 4
4 3
1 2 3 4
0 0
Sample Output
6 1 4 7 2 3 5
3 2 1 4
Problem Source

HNU 1'st Contest

AC:

 

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<cstring> 
#include<cstdlib>
#include <queue>

struct P
{
    P(int _i = 0, int _pass=0)
    {
        i = _i; pass = _pass;
    }
    int i, pass;
};
std::queue <P> q;

int main()
{
    int n, m, pass;
    P tmp, c;
    while (~scanf("%d%d", &n, &m) && n != 0 && m != 0)
    {
        while (!q.empty()) q.pop();
        for (int i = 0; i < n; ++i)
        {
            scanf("%d", &pass);
            tmp.i = i + 1; tmp.pass = pass;
            q.push(tmp);
        }
        while (!q.empty())
        {
            c.pass = m;
            while (!q.empty() && c.pass != 0) {
                tmp = q.front();
                q.pop();
                --c.pass;
                if (c.pass != 0) q.push(tmp);
                else { c = tmp; printf("%d", c.i); if (!q.empty()) printf(" "); else printf("\n"); };
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值