题目链接 : TOJ10006
10006 - Josephus Problem
Memory Limit: 65536KB
Description
Given a group of n men arranged in a circle under the edict that everymth man will be executed going around the circle until only one remains, find the positionL(n,m) in which you should stand in order to be the last survivor.
For example, n = 5 and m = 2, we number everyone from 1 to n based on their positions, and the entire process will be as follows:
In this case we should stand at position 3 thus we can escape from being executed.
Now you are given n and m, your task is to write a program to find the position of the last survivor.
Input
Two integers n and m, separated by a single space. (1 <= n,m <= 1000000).
Output
One integer, the position of the last survivor.
Sample Input
5 2
Sample Output
3
经典的约瑟夫问题
一开始想直接递归求解的。。
发现要爆栈 然后开始手写栈呗~
然后突然发现手写的栈里面存的东西没用!!!
果断直接就有 O(n) 的算法啊。。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
using namespace std;
int main()
{
// freopen("1.txt","r",stdin);
int n,m,i,s=0;
scanf("%d%d",&n,&m);
for(i=2;i<=n;i++)s=(s+m)%i;
printf("%d\n", s+1);
return 0;
}
附上手写栈代码
#include<cstdio>
int n,m;
int stack[1000005];
int main()
{
scanf("%d%d",&n,&m);
int ans=0,k=0;
while(n)
{
stack[k++]=m%n;
n--;
}
for(int i=k-1;i>-1;i--)
{
ans=(ans+stack[i])%(k-i);
}
printf("%d\n",ans+1);
return 0;
}