HOJ 1017 Joseff's problem II

来源:互联网 发布:温湿度数据记录生成器 编辑:程序博客网 时间:2024/05/16 12:09
“约瑟夫的问题”题目描述:

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from amongn 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 firstk are good guys and the lastk bad guys. You have to determine such minimalm 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 tok in the input file.

Sample Input

340
Sample Output
530
解题思路:主函数:首先用一个顺序表存储2*k个人,然后分别用0和1标记是好人还是坏人以此来之后作判断,用一个数组先读取数据并记录数据的个数,之后采用再利用循环和寻找坏人的函数来对每一个数据进行求解;
 寻找坏人的函数的实现:采用列举的方法对每一个数值逐一进行判断;判断数值是否满足题意时每次找到一个人后就将后面的数向前移,并减少总数,直到总数为0,则找到满足的答案;
#include <iostream>#include<stdio.h>#include<stdlib.h>#include<math.h>#define MAX 30using namespace std;typedef struct Seqlist{    int guys[MAX];    int n;}*PSeqlist;PSeqlist creatNulllist()//创建空的顺序表;{    PSeqlist plist;    plist = (PSeqlist)malloc(sizeof(struct Seqlist));    if(plist != NULL)    {        plist->n = 0;    }    else printf("out of speace!\n");    return plist;}void Findguys(PSeqlist plist,int n)//判断好人还是坏人,并求出满足的答案{    int m,i,j,k;    for(m = 1;;m++)//穷举,对每一个m进行试探;    {        k = n;        i = 0;         while(k > 0)        {            if((i + m) < k)//记录每次数了m后到了第几号;                j = i + m - 1;             else                j = (i + m - 1)%k;            if(k > n/2)            {                if(plist->guys[j] == 1) break;//如果在坏人完全消失之前轮到好人消失,则不对,退出            }            for(i = j;i < k;i++)            {                plist->guys[i] = plist->guys[i + 1];//消失了一个人,用后面的人取替他的位置            }            k--;            i = j;        }        if(k <= 0)//将所有人都正确剔出,是正确答案,输出        {            printf("%d\n",m);            return;        }    }}int main(){    int num[MAX];    int i,j,n = 0;    PSeqlist plist;    for(i = 0;;i++)//记录所有进行求解的数    {    scanf(" %d",&num[i]);    if(num[i] == 0) break;    n++;    }    for(i = 0;i < n;i++)    {        plist = creatNulllist();        for(j = 0;j < 2*num[i];j++)        {           if(j < num[i]) plist->guys[j] = 1;//是好人           else plist->guys[j] = 0;//是坏人        }        Findguys(plist,2*num[i]);    }    return 0;}

原创粉丝点击