F - System Overload(約瑟夫環問題)
Description
Recently you must have experienced that when too many people use the BBS simultaneously, the net becomes very, very slow.
To put an end to this problem, the Sysop has developed a contingency scheme for times of peak load to cut off net access for some buildings of the university in a systematic, totally fair manner. Our university buildings were enumerated randomly from 1 to n
Then a number m would be picked at random, and BBS access would first be cut off in building 1 (clearly the fairest starting point) and then in every mth building after that, wrapping around to 1 after n, and ignoring buildings already cut off. For example, if n
Your job is to write a program that will read in a number of buildings n and then determine the smallest integer m that will ensure that our CGB Building can surf the net while the rest of the university is cut off.
Input Specification
The input file will contain one or more lines, each line containing one integer nwith 3 <= n < 150, representing the number of buildings in the university.
Input is terminated by a value of zero (0) for n.
Output Specification
For each line of the input, print one line containing the integer m fulfilling the requirement specified above.
Sample Input
3 4 5 6 7 8 9 10 11 12 0
Sample Output
2 5 2 4 3 11 2 3 8 16
解題思路:約瑟夫環問題:找規律+遞推。題目的意思就是剛開始第1層樓是被斷電的,要求選出步長m使得每累加m層樓循環進行斷電,要求最後剩下的一層樓是第2層樓,簡單套一下約瑟夫的規律公式,再找出滿足情況的退出條件即可。註意:初始狀態是從第二層樓開始報數。
AC代碼:
1 #include<iostream> 2 using namespace std; 3 int main(){ 4 int n,s; 5 while(cin>>n&&n){ 6 for(int i=1;;++i){ 7 s=0; 8 for(int j=2;j<n;++j)s=(s+i)%j;//數學規律 9 if(s==0){cout<<i<<endl;break;}//如果此時s為0,即s+2==2,i就滿足情況,直接退出循環 10 } 11 } 12 return 0; 13 }
F - System Overload(約瑟夫環問題)