题目1188:约瑟夫环
时间限制:1 秒内存限制:32 兆特殊判题:否提交:1198解决:532
题目描述:
N个人围成一圈顺序编号,从1号开始按1、2、3......顺序报数,报p者退出圈外,其余的人再从1、2、3开始报数,报p的人再退出圈外,以此类推。
请按退出顺序输出每个退出人的原序号。
输入:
包括一个整数N(1<=N<=3000)及一个整数p。
输出:
测试数据可能有多组,对于每一组数据,
按退出顺序输出每个退出人的原序号。
样例输入:
7 3
样例输出:
3 6 2 7 5 1 4
来源:
时间限制:1 秒内存限制:32 兆特殊判题:否提交:1198解决:532
题目描述:
N个人围成一圈顺序编号,从1号开始按1、2、3......顺序报数,报p者退出圈外,其余的人再从1、2、3开始报数,报p的人再退出圈外,以此类推。
请按退出顺序输出每个退出人的原序号。
输入:
包括一个整数N(1<=N<=3000)及一个整数p。
输出:
测试数据可能有多组,对于每一组数据,
按退出顺序输出每个退出人的原序号。
样例输入:
7 3
样例输出:
3 6 2 7 5 1 4
来源:
2003-2005年华中科技大学计算机研究生机试真题
#include<stdio.h>
#include<malloc.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *LList;
int main(void)
{
int n, pass, temp, i, o[3000], x;
Node *P, *Q, *Pre, *PP;
LList circle;
while(scanf("%d%d", &n, &pass) == 2)
{
temp = n;
circle = (LList )malloc( sizeof(Node) );
P = circle;
for(i = 1; i <= n; i++)
{
PP = (Node *)malloc( sizeof(Node) );
PP->data = i;
P->next = PP;
P = P->next;
P->next = NULL;
}
P->next = circle->next;
Pre = circle;
P = circle->next;
while(n)
{
x = 0;
for(i = 1; i <= pass; i++)
{
x++;
if(x == pass){//abandon x==pass position
o[n] = P->data;
Q = P;
Pre->next = P->next;
P = P->next;
free(Q);
break;
}else{
Pre = P;
P = P->next;
}
}
n--;
}
for(i = temp; i > 1; i--)
printf("%d ", o[i]);
printf("%d\n", o[1]);
}//while
return 0;
}
/**************************************************************
Problem: 1188
User: true14fans
Language: C
Result: Accepted
Time:40 ms
Memory:912 kb
****************************************************************/