poj 1012 Joseph (約瑟夫問題),poj1012
Joseph
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 47657 |
|
Accepted: 17949 |
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
340
Sample Output
530
Source
約瑟夫問題的變形,開始對題意就理解了好久,這類題目主要要找到中間的公式;這道題就要知道 當前出局的位置 = (前一個出局的位置+m-1)%(2k-(k-1);
是從0開始數,這就是一個通式;明白了這個公式這個題相當於就做出了一半;這中間還有一個判別的條件,就是如果當前的位置如果<k,說明這種情況就不滿足了;
第一種方法:就直接可以對m的值進行枚舉,利用判別條件,找出合適的m值;
下面是代碼;這種思路好像200ms可以過;
//暴力+枚舉#include <cstdio>#include <cstring>int main(){ int k; int ans[20];//儲存當前的位置 int Joseph[20]={0}; //儲存合格m的值 for(k=1;k<14;k++) { int m=1; memset(ans,0,sizeof(ans)); for(int i=1;i<=k;i++) { ans[i]=(ans[i-1]+m-1)%(2*k-i+1); //遞推公式 if(ans[i]<k) { i=0; m++; } } Joseph[k]=m; } while(scanf("%d",&k)&&k!=0) { printf("%d\n",Joseph[k]); } return 0;}要想0ms過的,直接得出結果數組,然後再提交;
//直接枚舉 0ms#include <cstdio>#include <cstring>int main(){ int k; int Joseph[]={0,2,7,5,30,169,441,1872,7632,1740,93313,459901,1358657,2504881,1245064}; while(scanf("%d",&k)&&k!=0) { printf("%d\n",Joseph[k]); } return 0;}第二種方法,要挖掘題目中的隱含條件,我看了好久都沒看出來,代碼是參考別人的,這種46ms就可以過;最佳化了不少;
題目中的隱含條件;只剩下一個壞人的時候,下一個報數的人要麼是第1個人,要麼是第k+1個人;所以間隔就是m=s*(k+1)或者是 m=s*(k+1)+1;
粗略的證明一下,參考別人的:(這裡我也還有點沒懂)
僅剩一個壞人,圈長為k+1;設下一個報數人為第一個人時的時間間隔為m1;下一個報數人為第k+1個人時的時間間隔為m2;
由 (1+m1)%(k+1)=1 得出 m1= s*(k+1);
(k+1+m2)%(k+1)=1 得出 m2=s*(k+1)+1;
這樣我們就可以對m的枚舉最佳化剪枝,m是(k+1)的倍數或者是他的倍數+1;
#include <cstdio>#include <cstring>bool Joseph(int k,int m){ int n=2*k,x=0; while(n>k) { x=(x+m-1)%n;//遞推公式,算出當前出局的位置 if(x<k) //判別條件 return false; n--; } return true;}int main(){ int k; int result[20]={0}; for(k=1;k<14;k++) { for(int i=k+1;;i+=k+1) //對m枚舉進行最佳化 { if(Joseph(k,i)) //m是k+1的倍數或者倍數+1 { result[k]=i; break; } else if(Joseph(k,i+1)) { result[k]=i+1; break; } } } while(scanf("%d",&k)&&k) { printf("%d\n",result[k]); }}
總結一下:對於這一類題型要讀懂題目的題意,挖掘題目的隱含條件,多構思,理清思路才開始動手寫。
poj基礎水題
1004,求十二個數的平均數
2027,求是否滿足A>=B
3030
3062這兩個也傳說超水,暫時懶得去看。
1656,這個本來應該是不水的,估計題意原來是讓用線段樹或者樹狀數組做的,但是,題目裡的資料規模太小了,直接類比就過了。。也就成超級水題了。
先把這幾個A了吧。特別前幾個題難度可以和A+B齊名了。。