SWUST oj 536: The Josephus Problem

题目描述

The problem is named after Flavius Josephus, a Jewish historian who participated in and chronicled the Jewish revolt of 66-70C.E. against the Romans. Josephus, as a general, managed to hold the fortress of Jotapata for 47days, but after the fall of the city he took refuge with 40 diehards in a nearby cave. There the rebels voted to perish rather than surrender. Josephus proposed that each man in turn should dispatch his neighbor, the order to be determined by casting lots. Josephus contrived to draw the last lot, and as one of the two surviving men in the cave, he prevailed upon his intended victim to surrender to the Romans. Your task:computint the position of the survivor when there are initially n people.

输入

6

输出

5

解法一:

SWUST oj 536: The Josephus Problem_第1张图片

#include
#include
/*
当n%2=0 j(2n)=2j(n)-1
当n%2!=0 j(2n)=2j(n)+1 
*/
int J(int n){
	if(n==1)
	return 1;
	else{
		if (n%2==0){
			n/=2;
			return 2*J(n)-1;
		}
		else{
			n=(n-1)/2;
			return 2*J(n)+1;
		}
	}
}
int main(){
	int n;
	scanf("%d",&n);
	int ans=J(n);
	printf("%d\n",ans);
	return 0;
} 

原理:
偶数情况:J(2k,2)=2J(k,2)-1 n 奇数情况:J(2k+1,2)=2J(k,2)+1

解法二:

转化为二进制数(可以用数组存),左移一位(注意不是<<运算符)

//转换成二进制数
J(6)=J(110)=101=5J(7)=J(111)=111=7

你可能感兴趣的:(SWUST,OJ,数据结构)