约瑟夫环
int josephus(int n,int x)
{
if(n==1)
return 0;
else
return (josephus(n-1,x)+x)%n;
}
就是不断的往下层递归
Another Josephus
Time Limit: 1000 MS | Memory Limit: 131072 K |
Total Submit: 17(5 users) | Total Accepted: 6(3 users) | Rating: ![]() ![]() ![]() ![]() | Special Judge: No |
There are n students should be awarded after the school programming contest, to make the awards process more interesting, the coach use a new awarding method.
The n students stand in a circle, numbered from 0 to n-1. If the number of the rest students is odd, the next xth student will get his/her awards and leave the circle; if the number of the rest students is even, the next yth student with get his/her awards and leave the circle. The longer the student stays in the circle, the more awards he will get. Given the n, x, y, you should output the number of the student who will get the biggest awards (be the last one standing).
InputThe first line contains an integer T (T <= 25), then T cases follows.
In each case, there are 3 integers n, x, y in one line.
0 < n <= 1000000
0 < x, y <= 1000000
Output For each case, you should out put the number of the student who will get the biggest prize (be the last one standing) in a single line. Sample Input3
1 3 5
11 3 5
11 1 1
Sample Output0
8
10
HintThe second example's awarding order:
2, 7, 10, 5, 9, 6, 1, 3, 0, 4, 8
So the student number 8 will get the biggest prize.
Source"尚学堂杯"哈尔滨理工大学第六届程序设计竞赛#include<stdio.h>
#include<math.h>
int josephus(int n,int x,int y)
{
if(n==1)
return 0;
else if(n%2==1)
return (josephus(n-1,x,y)+x)%n;
else return (josephus(n-1,x,y)+y)%n;
}
int main()
{
int n,x,y;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&x,&y);
printf("%d\n",josephus(n,x,y));
}
}