1. 程式人生 > >搜狐2015年10月18日線上筆試題大題第一道答案

搜狐2015年10月18日線上筆試題大題第一道答案

考的的是約瑟夫環,還是挺簡單的,

15個教徒和15個非教徒在深海上遇險,必須將一半的人投入海中,其餘的人才能倖免於難,於是想了一個辦法:30個人圍成一個圓圈,從第一個人開始報數,每數到第九個人就將他扔入大海,如此迴圈進行直到僅餘15個人為止。問教徒怎麼站,才能使每次投入大海的都是非教徒。

是上述演算法題的翻版,只不過求的一串二進位制數而已

約瑟夫環(約瑟夫問題)是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重複下去,直到圓桌周圍的人全部出列。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct node
{
  int data1;
  struct node *next;
};
struct node * create(int n)
{
  struct node *head,*p,*q;
  int i;
  head=(struct node *)malloc(sizeof(struct node));
  head->data1=1;
  p=head;
  for(i=2;i<=n;i++)
  {
   q=(struct node *)malloc(sizeof(struct node));
   q->data1=i;
   p->next=q;
   p=q;
  }
  p->next=head;
  return(head);
}
struct node * deletelist(struct node *head,struct node *p)
{
  struct node *q;
  if(p==head)
	 {
	  head=p->next;
	  p->next=NULL;
  }
  else
  {
    q=head;
	while(q->next!=p)
		q=q->next;
	q->next=p->next;
  }
  free(p);
  return (head);
}
void printlist(struct node *head,int *arr,int m)
{
  struct node *p;
   printf("%5d",head->data1);
   arr[0]=1;
  p=head->next;
  while(p!=head)
  {
    printf("%5d",p->data1);
    arr[p->data1-1]=1;
	p=p->next;
  }
  printf("\n");
  int i;
  for(i=0;i<2*m;i++){
  	printf("%d",arr[i]);
  }
  

}
main()
{
 int m,k;
 scanf("%d%d",&m,&k);
 struct node *head,*p,*q;
 int num=2*m,n;
 head=create(2*m);
 p=head;
 while(num>m)
 {
   //printf("hahah");
   n=1;
   while(n<k)
   {
	   p=p->next;
	   n++;
   }
   q=p;
   p=p->next;
   head=deletelist(head,q);
   num--;

 }
 int *arr = (int*)malloc(sizeof(int)*m*2);
 int *a;
 for(a=arr;a<arr+m*2;a++){
 	*a=0;
 }
 printlist(head,arr,m);
}
迴圈的單鏈表,在不停的找第k個元素,直到所剩下的元素為原來數目的一半。