来源:牛客网:

题目描述

1st Academy is an international leadership training academy based in Kuala Lumpur. Every year, the company trains thousands of people to be supplied to companies around the world. To be fair amongst all the trainees, the company will do the selection process using numbering system. The trainees will choose a number from 1 to N, and one number is not limited to only one trainee. The N represents the total number of companies that request trainees from the academy. A number, M, would be picked at random, and the selection starts with a trainee whose number is 1, and then in every M’th people after that, wrapping around to 1 after N, and ignoring trainees already selected. For example, if N = 15 and M = 6, trainees would be selected in the order: 6, 12, 3, 10, 2, 11, 5, 15, 13, 9, 14, 4, 1, 8, 7. All the selected trainees except the last one (which is number 7) will be supplied to companies outside of Malaysia.
However, Leong preferred to stay and work in Malaysia. To him, there is no better place other than Malaysia. He does not mind being located anywhere as long it is Malaysia. As a friend of him, you could help him to choose a number that will save him from being located outside.
Input
输入描述:
Input will consist of a series of lines, each line containing the number of companies (N) with 1 \leq N \leq 15001≤N≤1500, and a skipping value (M) with 1 \leq M \leq 501≤M≤50. The values will be terminated by a line consisting of double zeros (0 0) as shown in sample input output.
输出描述:
Output will consist of a series of lines, one for each line of the input. Each line will consist of the number M according to the above scheme.
示例1
输入
复制

15 6 
550 23 
0 0

输出
复制

7 
470

题意:

已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。问最后一个出列的人是多少号

题解:

经典约瑟夫环问题
我们看一下样例:
15 6
依次出列的是:
6, 12, 3, 10, 2, 11, 5, 15, 13, 9, 14, 4, 1, 8, 7.
最后是7,7就是我们的答案
这个题麻烦在已经出列的人不能再被算在里面
第一次6出列后,再往后数数时就不能再算6,那该怎么做?
我们可以这样,当指针指向第一个要出列的数6时,6出列后,
原本是:
1 2 3 4 5 6 7 8 9 .....
更改为:
1 2 3 4 5 7 8 9....
让6后面的每个数向前覆盖,然后总量也从15变为14,(第15位变成0)
指针也向前移动,因为6已经不存在了
一直模拟这个过程即可,当只剩下两个数,且存在有一个数已经被移开,那最后吃鸡的数就是我们要的

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=2000;
int pos[maxn];
int main()
{
    int m,n;
    while(cin>>m>>n)//总人数 以n循环
    {
        if(m==0||n==0)break;
        for(int i=1;i<=m;i++)pos[i]=i;//给每个数一个编号
        int temp=0;

        while(true)
        {
            temp+=n;//
            temp%=m;//
            if(temp==0)temp=m;//指向最后一个人 
            for(int i=temp;i<m;i++)pos[i]=pos[i+1];//第temp的数不存在,编号前移
            pos[m]=0;//去掉一个人 
            m--; //人数少一
            temp--;
            if(pos[2]==0)break;//当倒数第二个数删除以后 
        }
        cout<<pos[1]<<endl;
    } 
    return 0;
}