永发信息网

Josephus环问题

答案:2  悬赏:40  手机版
解决时间 2021-01-26 22:18
  • 提问者网友:绫月
  • 2021-01-25 23:17
设n个人围坐在一圆桌周围,依次编号为1,2,...,n,从第s个人从1开始依次报数,数到m的人出列,然后从出列的下一个人重新开始报数,数到m的人又出列,…,如此反复直到所有的人全部出列为止。对于任意给定的n,s和m,输出按出列次序得到的n个人员的序列。(数据结构问题,请分别用顺序表和链表解决此问题,并自编多组数据测试)
需要输入:人数n、第一个开始者的编号s以及报数出列编号m

急求答案,求C语言高人帮帮忙
最佳答案
  • 五星知识达人网友:长青诗
  • 2021-01-26 00:26
#include
#include
int a[100];
int main()
{
int n,s,m,i,t,j;
while(scanf("%d%d%d",&n,&s,&m)&&(n||s||m))
{
memset(a,-1,sizeof(a));
for(i=1;i<=n;i++)
a[i]=i;
t=n;
for(i=s,j=1;t>1;i++)
{
if(a[i]==0)
i++;

if(i>n)
i-=n;
if(a[i])
j++;
if(j==m+1)
{
printf("%d,",a[i]);
t--;
j=1;
a[i]=0;
}

}
for(i=1;i<=n;i++)
if(a[i])
{
printf("%d\n",a[i]);
break;
}
}
return 0;
}
全部回答
  • 1楼网友:孤老序
  • 2021-01-26 00:44

//循环链表解决 #include <stdio.h> #include <stdlib.h> typedef struct lnode {  int data;  struct lnode *next; }lnode; void josephus(int n, int k, int m) {  lnode *head, *r, *list, *curr;    head = (lnode *)malloc(sizeof(lnode));  head->data = 1;  head->next = head;  curr = head;  int i;  for(i=1; i<n; i++)  {   lnode *p = (lnode *)malloc(sizeof(lnode));   p->data = i+1;   p->next = curr->next;   curr->next = p;   curr = p;  }  int x;  list = head;  while(--k)  {   r = list;     list = list->next;  }  printf("%d\t%d\n", list->data, r->data);  while(n--)  {   int j;   for(j=0; j<m-1; j++)   {    r = list;    list = list->next;   }   r->next = list->next;   printf("%d\t", list->data);   free(list);   list = r->next; //list points to the next element which had been deleted  } }

int main() {  int n, k, m;  printf("please input the total of the people in josephus circle: ");  scanf("%d", &n);  printf("please input the starting position: ");  scanf("%d", &k);  printf("please input the dead number: ");  scanf("%d", &m);  josephus(n, k, m);  printf("\n");  return 0; }

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯