采用顺序存储结构编写程序实现Josepus问题
设有N个人围坐在一起,从第S个人开始数数到第M的人就出列,然后以出列者的下一个开始重新按上述方法数数到M就出列,如此重复直到所有人都出列,要求给出每个人的出列次序,既求一个按出列次序排列的N个人的顺序
#include <malloc.h> #include <limits.h> #include<stdio.h> #include<io.h> #include<process.h>
#define listsize 100 #define Lincremment 10
#define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define OVERFLOW -2
typedef int ElemType; typedef int Status;
typedef struct { ElemType *elem; int length; int listsize; }SqList;
Status InitList(SqList &L) { L.elem=(ElemType *)malloc(listsize * sizeof(ElemType)); if(!L.elem) exit(OVERFLOW); L.length = 0; L.listsize = listsize; return OK; }
Status ListInsert(SqList &L,int i,ElemType e) { int i; SqList newbase; ElemType e; ElemType *q; ElemType *p; if(i < 1 || i > L.length) return ERROR; if(L.length >= L.listsize) { newbase = (ElemType *)realloc(L.elem,(L.listsize + Lincremment) * sizeof(ElemType)); if(!newbase) exit(OVERFLOW); L.elem = newbase; L.listsize += Lincremment; } q = &(L.elem[i - 1]); for(p = &(L.elem[L.length - 1]);p >= q;--p) *(p - 1) = *p; *q = e; ++L.length; return OK; } Status DeleteList(SqList &L,int i,ElemType &e) { int i; ElemType e; ElemType *p; ElemType *q; if((i < 1) ||(i > L.length)) return ERROR; p = &(L.elem[i-1]); e = *p; q = L.elem + L.length - 1; for(++p;p <= q;++p) *(p-1) = *p; --L.length; return e }
main() { int n; int m; int s; int a[listsize]; int i; int N; SqList L; scanf("%d",&n); scanf("%d",&m); scanf("%d",&s); for(i = 1;i <= n;i++) ListInsert(&L,i,i);
N = s + m; a[0] = ListDelete(&L,N,&e); for(i = 1;i < n;i++) { for(i = 1;i <= m;i++) { if(N > L.length) N = N + m - 1 - L.length; else N = N + m - 1; if(N <= L.length) break; } a[i] = ListDelete(&L,N,&e); } for(i = 0;i < n;i++) { printf("a[i] = %d\n ",a[0]); } }