当前位置: 代码迷 >> 综合 >> 约瑟夫问题(Josephus)
  详细解决方案

约瑟夫问题(Josephus)

热度:69   发布时间:2023-12-15 04:51:25.0

共9个坐一圈,由每次第2人开始报数,报到第3个出圈,求出圈顺序。
vector.h

#ifndef vector_h__
#define vector_h__# include <stdio.h>
# include <malloc.h>enum boolen{TRUE, FALSE};typedef int ElementType;
typedef enum boolen BOOL;typedef struct Vector_def{ElementType * data;int sz;int len;
}Vector;
void initVector(Vector* V,int sz);
BOOL RemoveNode(Vector* V, int i);
BOOL InsertNode(Vector* V, ElementType x, int i);
void printout(Vector* V);
BOOL GetNode(Vector* V, int i, ElementType* x);#endif // vector_h__

vector.h

#include "vector.h"void initVector(Vector* V,int sz){if (sz > 0){V->sz = sz;V->len = 0;V->data = (ElementType *)malloc(sizeof(ElementType)*sz);if (V->data == NULL)puts("Get memory error.");}else{puts("sz error.");}
}BOOL RemoveNode(Vector* V, int i){int j;if (i<0 || i>V->len){puts("The location is error.");}else{for (j=i; j<V->len; j++){V->data[j-1] = V->data[j];}V->len--;}return TRUE;
}BOOL InsertNode(Vector* V, ElementType x, int i){int j;if (i<0 || i>V->len || V->len == V->sz)return FALSE;for (j=V->len-1; j>=i; j--)V->data[j+1] = V->data[j];V->len++;V->data[i] = x;return TRUE;
}BOOL GetNode(Vector* V, int i, ElementType* x){if (i<0 || i>V->len)return FALSE;*x = V->data[i];
// RemoveNode(V, i);return TRUE;
}
void printout(Vector* V){int i;for (i=0; i<V->len; i++)printf("%d ", V->data[i]);printf("\n");
}

main.c

#include "vector.h"void Josephus(Vector* v, int n, int s, int m);
int main(){Vector V;Josephus(&V, 9, 2, 3);printout(&V);return 0;
}//************************************
// Method: Josephus
// FullName: Josephus
// Access: public 
// Returns: void
// Qualifier:
// Parameter: Vector * v
// Parameter: int n 一共的人数
// Parameter: int s 报数开始位置
// Parameter: int m 报到m停止
//************************************
void Josephus(Vector* v, int n, int s, int m){int i, j, k;ElementType x;initVector(v, n);for (i=0; i<n; i++)InsertNode(v, i+1, i);for (i=n; i>=1; i--){k = (s+m-1)%i;if (k==0)k =i;GetNode(v, k-1, &x);RemoveNode(v, k);InsertNode(v,x,n-1);}
}

程序运行图