hdu 1443 Joseph (约瑟夫环问题)

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
 

Source

   思路: 最开始看到这个题目的时候整个人都是懵逼的,然后就想可能是一道找规律的题目,然而一直没有找到规律,卡了两天,我用计算机从k+1开始计算,找出最小的那一个m,终于卡出了1~13的答案,然后就交了、就A了。后面网上看了一些博客,然后才发现,自己先前就卡在简化了,简化完成后就可以直接得出答案了···········

代码:

#include<iostream>//这是卡出答案后直接输出的代码
using namespace std;
int a[15]={0,2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881};
int main()
{
    int n;
    while(cin>>n&&n)
        cout<<a[n]<<endl;
    return 0;
}
#include<iostream>
using namespace std;
int vis[16]= {0};
int fond(int k)
{
    if(vis[k])                                  //如果k是曾经出现过的,已经计算了答案的,就直接输出;
        return vis[k];
    else
    {
        for(int i=k+1;; i++)                   //从k+1开始找
        {
            int sum=k*2,flag=0;                //sum为所剩的人数,flag来标记一个数是否为后k个数,如果flag==1,这个i不用继续找下去了;
            for(int j=i; flag==0; j+=i-1)
            {
                if(j>sum)
                    j= j%sum ? j%sum:sum;
                if(j<=k)
                    break;
                else
                    sum--;
                if(sum==k)
                    flag=1;
            }
            if(flag)
            {
                vis[k]=i;
                return vis[k];
            }
        }
    }
}
int main()
{
    int n;
    while(cin>>n&&n)
        cout<<fond(n)<<endl;
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章