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


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