码迷,mamicode.com
首页 > 其他好文 > 详细

F - System Overload(约瑟夫环问题)

时间:2018-07-14 00:19:33      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:bre   desc   iostream   tin   hose   ios   example   思路   目的   

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. XWB is number 1, CaoGuangBiao (CGB) Building is number 2, and so on in a purely random order.
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=17 and m=5, net access would be cut off to the buildings in the order [1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7]. The problem is that it is clearly fairest to cut off CGB Building last (after all, this is where the best programmers come from), so for a given n, the random number m needs to be carefully chosen so that building 2 is the last building selected.

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(约瑟夫环问题)

标签:bre   desc   iostream   tin   hose   ios   example   思路   目的   

原文地址:https://www.cnblogs.com/acgoto/p/9307961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!