9496 Josephus问题
时间限制:1000MS 内存限制:65535K
提交次数:0 通过次数:0
题型: 编程题 语言: 无限制
Description
编写算法解决Josephus问题:设有n个人围在一个圆桌周围,现从第s个人开始报数,数到第m个人又出列…如此反复直到所有的人全部出列为只止。
Josephus问题是:对于任意给定的n,s和m,求出按出列次序得到的n个人员的序列。
Input
输入表示n,s,m的三个值,用空格分隔
Output
输出出列序列
Sample Input
8 3 4
Sample Output
6 2 7 4 3 5 1 8
Provider
sjjg
#include<stdio.h> #include<malloc.h> typedef struct CriCurt{ int data, flag; struct CriCurt *next; }Cri, *CriStr; typedef struct Point{ CriStr base, front; }Point; int InitPoint(Point* &T, int n) { int i, e; CriStr str, stp; T->base = (CriStr)malloc(sizeof(CriCurt)); T->base->data = n; T->base->flag = 1; T->base->next = NULL; T->front = T->base; for(i=1; i<=n; ++i) { if(!(str = (CriStr)malloc(sizeof(CriCurt)))) return 0; str->data = i; str->flag = 1; str->next = NULL; T->front->next = str; T->front = T->front->next; } T->front->next = T->base->next; return 1; } int ifflag(Point* T) { CriStr str, stp; str = T->base->next; while(str != T->front) { if(str->flag == 1) return 1; str = str->next; } if(str->flag == 1) return 1; return 0; } int Joseph(Point* &T, int s, int m) { CriStr str; int i, j, count = 0; str = T->base; for(i=1; i<s; ++i) str = str->next; while(ifflag(T) != 0) { for(i=1; i<=m; ++i) { str = str->next; while(str->flag == 0) str = str->next; } if(count++ == 0) printf("%d", str->data); else printf(" %d", str->data); str->flag = 0; } printf("\n"); } int FreePoint(Point* &T) { CriStr str, stp, stq; str = T->base->next; stp = str->next;; while(str != stp) { stq = stp->next; free(stp); stp = stq; } free(str); free(T->base); return 1; } int main() { Point* T; T = (Point*)malloc(sizeof(Point)); int n, s, m; T->base = T->front = NULL; scanf("%d%d%d", &n, &s, &m); InitPoint(T, n); Joseph(T, s, m); FreePoint(T); return 0; }
解题报告:
自学数据结构后学校OJ上的最后一道实验题,才发现原来不是这么好受的,WA了5次,想死的心都有了,对不起,只是想死的心,不是去死的心,野指针到处乱飞,最后弄得
不欢而散,无知竟是如此地可怕,下次不敢了!以此为戒,菜鸟坠地常有的事,加上约瑟夫环较为多见,这是最简单的一题,代码不简,为自己留着。