1. 程式人生 > >ACM刷題之HDU————Joseph

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]);
	}
	
}

中間字母比較多,不要弄混就好。。

方法已經在在註釋中了,自己在草稿紙上體會下就知道怎麼寫了。