LightOJ - 1179-Josephus Problem(约瑟夫环)
链接:
https://vjudge.net/problem/LightOJ-1179
题意:
The historian Flavius Josephus relates how, in the Romano-Jewish conflict of 67 A.D., the Romans took the town of Jotapata which he was commanding. Escaping, Josephus found himself trapped in a cave with 40 companions. The Romans discovered his whereabouts and invited him to surrender, but his companions refused to allow him to do so. He therefore suggested that they kill each other, one by one, the order to be decided by lot. Tradition has it that the means for affecting the lot was to stand in a circle, and, beginning at some point, count round, every third person being killed in turn. The sole survivor of this process was Josephus, who then surrendered to the Romans. Which begs the question: had Josephus previously practiced quietly with 41 stones in a dark corner, or had he calculated mathematically that he should adopt the 31st position in order to survive?
Now you are in a similar situation. There are n persons standing in a circle. The persons are numbered from 1 to n circularly. For example, 1 and n are adjacent and 1 and 2 are also. The count starts from the first person. Each time you count up to k and the kth person is killed and removed from the circle. Then the count starts from the next person. Finally one person remains. Given n and k you have to find the position of the last person who remains alive.
思路:
从最后一个状态推到开始状态。
给例子:n = 10, k = 4
原环 0 1 2 3 4 5 6 7 8 9
旧环 0 1 2 4 5 6 7 8 9
新环 6 7 8 0 1 2 3 4 5
新环重新标号。可以推出新环的标号。(旧环标号-k值)%旧人数。
由此从新环可以推出旧环的标号。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<vector>
#include<map>
using namespace std;
typedef long long LL;
const int INF = 1e9;
const int MAXN = 1e6+10;
const int MOD = 1e9+7;
int main()
{
int t, cnt = 0;
int n, k;
scanf("%d", &t);
while(t--)
{
printf("Case %d: ", ++cnt);
scanf("%d%d", &n, &k);
int res = 0;
for (int i = 2;i <= n;i++)
res = (res+k)%i;
printf("%d\n", res+1);
}
return 0;
}