這裏並不是原始的Josephus問題,而是其“通用版”,而歷史上的那個只是個特殊情況
下面直接給代碼:
#include <stdio.h>
#include <stdlib.h>
struct People;
typedef struct People *PtrToPeople;
struct People
{
int Position;
PtrToPeople Next;
};
typedef PtrToPeople Curcle;
typedef PtrToPeople Position;
void Insert(Position P,int e)
{
Position TmpCell;
TmpCell = malloc(sizeof(struct People));
TmpCell->Position = e;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
Position FindPre(Position P)
{
Position T = P;
for(;;)
if(T->Next == P)
return T;
else
T = T->Next;
}
Position DeleteAndPrint(Position P)
{
printf("%d ",P->Position);
Position T = FindPre(P);
T->Next = P->Next;
free(P);
return T->Next;
}
/* 輸出被選中的,剩下最後一個是winner */
int main()
{
int N,M,i;
/* N表示總數,M表示跳格數 */
scanf("%d%d",&M,&N);
Curcle C = malloc(sizeof(struct People));
C->Position = 1;
C->Next = C;
for(i = 2; i <= N; i++)
{
Insert(C,i);
C = C->Next;
}
Position P = C->Next;
for(;;)
{
int j;
for(j = 0; j < M; j++)
{
P = P->Next;
}
if( P->Next == P )
{
break;
}
else
P = DeleteAndPrint(P);
}
return 0;
}