题目:
有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;
}