先看一下规矩的链表做法吧
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n, m, b;
struct People {
int Num;
People *Next;
};
People *Head, *Temp;
void Cycle()
{
int i = 0;
Head = new People;
Temp = Head;
while(i < n)
{
i++;
Temp->Num = i;
if(i == n)
{
Temp->Next = Head;
}
else Temp->Next = new People;
Temp = Temp->Next;
}
return;
}
int main()
{
while(cin>>n>>m && n && m)
{
Cycle();
People *Now;
Now = Head;
while(Now->Next != Now)
{
int x = 0;
while(x < m-1)
{
x++;
Now = Now->Next;
}
Now->Next = Now->Next->Next;
}
Now->Num--;
if(Now->Num == 0) cout<< n << endl;
else cout << Now->Num << endl;
}
return 0;
}
附代码↓
↓
↓
注释都在程序里:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
long long n, m;//说好的数据很水,但还是需要开到longlong型,有点难过
void run()
{
scanf("%lld %lld", &n, &m);//输入n和m,n个人,数到m的人出列
if (m == 2)//一种特殊情况需要自(chao)己(lai)的推理
{
long long t = 1;
while ((t << 1) <= n) t <<= 1;//2的r次方加上s,使s尽量小
printf("%lld",(n - t) * 2 + 1);//就输出
return;//返回
}
else
{
int f = 0;
for (int i = 2; i <= n; i++)
{
int g = f;
f = (g + m) % i;//一个从网上找来的公式..自己下来还需要推一下
}
printf("%d", f + 1);
}
}
int main()
{
//#ifndef LOCAL ←托哥上课时讲的新操作,有点骚
// freopen("joseph.in", "r", stdin);
// freopen("joseph.out", "w", stdout);
//#endif
run();//调用函数
return 0;
}