P8671约瑟夫环
这是本蒟蒻的第一篇题解,大佬轻点喷。
“约瑟夫环” (普及+/提高),这一看就不简单。
本题下标从
题目大意
有
Algorithm 1 模拟 O(nk)
首先可以将人不断入队和出队,当有人报的数到达了
下面是我的模拟代码,很显然时间复杂度太高了。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
cin >> n >> k;
queue<int> peo;
for(int i = 1;i <= n;i++)
{
peo.push(i);
}
int cnt = 0;
while(peo.size() != 1)
{
int name = peo.front();
cnt++;
if(cnt == k)
{
peo.pop();
cnt = 0;
continue;
}
peo.pop();
peo.push(name);
}
cout << peo.back();
return 0;
}
Algorithm 2 使用约瑟夫环的递推公式 O(n)
设
-
F(1)=0 -
F(n)=(F(n-1)+k)\bmod n 于是就可以求答案了。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,k,s = 0;
cin >> n >> k;
for(int i = 2;i <= n;i++)
{
s=(s+k)%i;
}
cout << s+1; //答案初始下标为1
return 0;
}
题目传送门
鸣谢 @cqrcqr。