ACM刷题之HDU————Joseph

Joseph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2251    Accepted Submission(s): 1370


Problem 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
 



第一次用结构体做题。。

这题我也是看了一个叫做 C_Ychen 的博主写的方法,才慢慢码出来的。

下面是自己写的ac代码,其中的思想是借鉴了 C_Ychen 博主的

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct joseph
	{
		int now;
		int next;
		int pre;
	}joseph;
int main()
{	
	joseph a[30];
	int m,n,rec1,rec2,i,count,total,x;
	int j[14];
	j[1]=2;
	for(i=2;i<=13;i++)
	{
		count=0;
		for(m=2;count!=i*2;m++)
		{
			for(n=0;n<2*i;n++)
			{
				a[n].now=n;
				a[n].next=n+1;
				a[n].pre=n-1;
			}                      //赋值 成环 
			a[0].pre=a[i*2-1].now;
			a[i*2-1].next=a[0].now;
			count=0;
			rec1=0;
			total=i*2;
			//////////下面开始去掉人//////
			while(count<i)
			{
				for(n=0;n<(m-1)%total;n++)			//取余 数人 
				{
					rec1=a[rec1].next;			//模拟点人 
				}
				rec2=a[rec1].next;				//记录被点的人的下一个人 下次从这里开始点人
				a[a[rec1].pre].next=a[rec1].next;  //开始删掉这个a[rec1]  把他的上一个人的下一个人改为a[rec1]的下一个人
				a[a[rec1].next].pre=a[rec1].pre;   //t同上 吧下一个人的前一个人改为a[rec1]的前一个
			
				if((a[rec1].now>=0)&&(a[rec1].now<i))
				{
					break;
				} 
				else
				{
					count++;
					rec1=rec2;
					
				}total--;
			}
			if(count==i)
			{
				j[i]=m;
				break;
			}		
		}
	}
	while(scanf("%d",&x)!=EOF)
	{
		if(x==0)
			break;
		printf("%d\n",j[x]);
	}
	
}

中间字母比较多,不要弄混就好。。

方法已经在在注释中了,自己在草稿纸上体会下就知道怎么写了。

你可能感兴趣的:(函数,ACM,结构体,杭电)