约瑟夫问题
N个人围成一圈,从第一个开始报数,第M个将出列,最后剩下一个,其余人都将已出列。问出列的顺序?例如N=6,M=5,出列的序号为5,4,6,2,3。最后剩下1号。
(数组)
[ 本帖最后由 chao41091153 于 2010-5-30 16:10 编辑 ]
程序代码:
int Josephus1(int n,int s,int m,int *B){
int i,k,tmp,j;
if(m<0||s<1||n<0)
return 0;
else{
//向量B初始化
for(i=0;i<n;i++)
B[i]=i+1;
//算法
i=s-1;
for(k=n;k>1;k--)
{
i=(i+m-1)%k;
if(i!=k-1)
{
tmp=B[i];
for(j=i;j<k-1;j++)
B[j]=B[j+1];
B[k-1]=tmp;
}
}
for(k=0;k<n/2;k++)
{
tmp=B[k];
B[k]=B[n-k-1];
B[n-k-1]=tmp;
}
}
return 1;
}
程序代码:#include "malloc.h"
#define null 0
typedef struct node {
int data;
struct node *next;} JD;
void creater(JD *head,int n)
{
int i;
JD *L,*s,*p;
L=(struct node *)malloc(sizeof(struct node));
L->next=null;
s=L;
for(i=1;i<=n;i++)
{
p=(JD *)malloc(sizeof(JD));
p->data=i;
s->next=p;
s=p;
}
head->next=p;
p->next=L->next;
}
int delet(JD *t)
{
JD *q;int e;
q=t->next;
t->next=q->next;
e=q->data;
free(q);
return e;
}
int Josephus2(int n,int s,int m,int *B)
{ if(m<0||s<1||n<0)
return 0;
JD *head;
static JD *t;
head=(struct node *)malloc(sizeof(struct node));
head->next=null;
int j=0,i,k;
creater(head,n);
t=head;
for(i=0;i<s;i++)
t=t->next;
while(t!=t->next)
{
if(m!=1)
{
for(k=1;k<m;k++)
t=t->next;
}
B[j++]=delet(t);
}
B[j]=t->data;
return 1;
}
程序代码:
#include <stdio.h>
#include <stdlib.h>
int N = 5;
int M = 9;
typedef struct node* link;
struct node
{
int item;
link next;
};
int main(void)
{
int i;
link t = malloc(sizeof(*t)), x = t;
t->item = 1; t->next = t;
for (i = 2; i <= N; i++)
{
x = (x->next = malloc(sizeof*x));
x->item = i; x->next = t;
}
while (x != x->next)
{
for(i = 1; i < M; i++)
x->next = x->next->next;
N--;
}
printf("%d\n", x->item);
return 0;
}
