题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5643
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 859 Accepted Submission(s): 476
Problem Description
In order to remember history, King plans to play losephus problem in the parade gap.He calls n(1≤n≤5000) soldiers, counterclockwise in a circle, in label 1,2,3...n.
The first round, the first person with label 1 counts off, and the man who report number 1 is out.
The second round, the next person of the person who is out in the last round counts off, and the man who report number 2 is out.
The third round, the next person of the person who is out in the last round counts off, and the person who report number 3 is out.
The N - 1 round, the next person of the person who is out in the last round counts off, and the person who report number n−1 is out.
And the last man is survivor. Do you know the label of the survivor?
Input
The first line contains a number T(0<T≤5000), the number of the testcases.
For each test case, there are only one line, containing one integer n, representing the number of players.
Output
Output exactly T lines. For each test case, print the label of the survivor.
Sample Input
2
2
3
Sample Output
2
2
Hint: For test case #1:the man who report number $1$ is the man with label $1$, so the man with label $2$ is survivor. For test case #1:the man who report number $1$ is the man with label $1$, so the man with label 1 is out. Again the the man with label 2 counts $1$, the man with label $3$ counts $2$, so the man who report number $2$ is the man with label $3$. At last the man with label $2$ is survivor.
思路:今天刚系统的学习了约瑟夫环,没想到还是卡住了,参照了一位大牛的博客,自己很勉强的写出来了,总之,还是需要自己去推导和演算的,不能眼高手低!(约瑟夫环的详解请看我这篇博客,里面有细腻的叙述 【点这里】)
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 5e3+10;
int ans[maxn],dp[maxn];
int solve(int m)
{
if(m==0)
return 0;
if(m==1)
return 1;
else //m>=1时递推关系建立,依次打好表
{
dp[1] = 0;
int k=m-1;
for(int i=2;i<=m;i++)
{
dp[i] = (dp[i-1] + (k--))%i;
}
return dp[m] + 1;
}
}
int main()
{
for(int i=0;i<=maxn;i++)
ans[i] = solve(i);
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%d\n",ans[n]); //按照已经打好的表进行输出,省时间
}
return 0;
}