poj 1012 小白算法练习 Joseph 约瑟夫环 打表

Joseph
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 54669 Accepted: 20916

Description

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from among n people, numbered 1, 2, . . ., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved. 

Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy. 

Input

The input file consists of separate lines containing k. The last line in the input file contains 0. You can suppose that 0 < k < 14.

Output

The output file will consist of separate lines containing m corresponding to k in the input file.

Sample Input

3
4
0

Sample Output

5
30

翻译

2k个人围成一圈,前面k个人是好人,后面k个人是坏人,循环报数,输入m代表这在m个人停止,报数报到的人就死了,我们的目的是首先杀死所有的坏人,请找到m

捷径

#include<iostream>
using namespace std;
int i;//假设值m 
int K;//k good guys
int joseph[20];
int Kgood(int i_c,int kgood,int kbad,int index){   //i__m;index__循环了多少次__循环kbad次结束 
	if(index==K) return 1; 
	int x=i_c%(kgood+kbad);         //当前轮到的人 
	if(x==0) x=(kgood+kbad);
	int y=(kgood+kbad)-x;           //轮到人的后面还有多少bad guys 
	if(x<=kgood) return 0;          //如果轮到good guys则不是这个数 
	Kgood( i-y,kgood,kbad-1,index+1);					
}

int main(){
	
//	freopen("E:1001.txt","r",stdin);
	while( (cin>>K) && K!=0)
	{
		if(joseph[K]!=0)
		{
			cout<<joseph[K]<<endl;
		}
		for(i=1;i<INT_MAX;i++)
		{
			if( Kgood(i,K,K,0)==1 )  break;
		}
		joseph[K]=i; 
		cout<<i<<endl;
	}
}
//这是不知道约瑟夫环的做法
利用这个纯暴力的方法把1-13先求出来,那只笔记下来,然后case 1=5,case 2=30,写下来然后再提交代码,我一开始就是这样水的。。。

代码

我们得先了解一下约瑟夫环点击打开链接 ,点击打开链接

#include<iostream>
#include<cstring> 
using namespace std;
int main(){
	int person[30];
	int joseph[15];
	memset(person,0,sizeof(person));
	memset(joseph,0,sizeof(joseph));
	int K;
	while( (cin>>K) && K!=0)
	{
		if(joseph[K]!=0){
			cout<<joseph[K]<<endl;
			continue;
		} 
		int numofperson=2*K;
		int m=K+1;//报数杀死的人//最小肯定是K+1,最大是2K 
		
		memset(person,0,sizeof(person));//清空一下 //哭
		
		for(int i=1;i<=K;i++) 
		{
			person[i]=(person[i-1]+m-1)%(numofperson-i+1);
			if(person[i]<K)//good guys can not kill 
			{
				m++;
				i=0;//i不是=1;因为后面还有i++
			}	
		} 
		joseph[K]=m;
		cout<<m<<endl; 
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值