| Home | Web Board | ProblemSet | Standing | Status | Statistics |
阅读,思考,分享,K题。编程优化人生!
Problem B: Joseph Problem
Time Limit: 4 Sec Memory Limit: 100 MB
Submit: 348 Solved: 137
[Submit][Status][Web Board]
Description
The Joseph's problem is notoriously known. From among n people, numbered 1, 2, . . ., n, standing in circle. Starting from sth and 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, s = 1 and m = 5, then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved. (1<= n <=20000, s>=1, m >=1)
Input
There are multiple test cases. For each case, there is a line contains three positive integers, n, s and m..
Input is terminated by EOF.
Output
For every test case, output a single line containing the number of the person who may be saved.
Sample Input
13 1 515 2 5
Sample Output
6
2
问题分析:
三个元素,共有n(1《=n《2000)个人,从第s(》=1)个开始报数,报到m(》=1)的人出局,求最后剩下的人的编号。F(n)代表总人数为n时(此时的编号从0开始编号),最后剩下人的编号。有数学公式F(n)=(F(n-1)+m)%n。最后从第s个开始报数,所以最后剩下的编号为(F(n)+s)%n;
代码如下:
#include <iostream>
using namespace std;
int main()
{
int n(6), s(0), m(5);
while (cin >> n >> s >> m) {
int t = 0;
for (int i(2); i <= n; ++i) {
t = (t + m) % i;
}
t = (t + s) % n;
cout << t << endl;
}
return 0;
}
本文探讨了经典的约瑟夫问题,并提供了一种简洁的算法实现。通过递推公式F(n)=(F(n-1)+m)%n计算在特定规则下最后一个幸存者的编号。
297

被折叠的 条评论
为什么被折叠?



