TOJ 10006 Josephus Problem

题目链接 : TOJ10006


 

10006 - Josephus Problem

Time Limit: 1000MS
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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值