[1197]约瑟夫问题 (循环链表)SDUT
生活随笔
收集整理的這篇文章主要介紹了
[1197]约瑟夫问题 (循环链表)SDUT
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
約瑟夫問題
Time Limit: 1000ms?? Memory limit: 65536K??有疑問?點這里^_^
題目描述
n個人想玩殘酷的死亡游戲,游戲規則如下:?n個人進行編號,分別從1到n,排成一個圈,順時針從1開始數到m,數到m的人被殺,剩下的人繼續游戲,活到最后的一個人是勝利者。
請輸出最后一個人的編號。
輸入
輸入n和m值。輸出
輸出勝利者的編號。示例輸入
5 3示例輸出
4 #include <stdio.h> #include <stdlib.h> struct node {int data;struct node *next; }; int n,m; struct node *creat()//循環鏈表的建立 {struct node *head,*tail,*p;int i;head=(struct node *)malloc(sizeof(struct node));head->next=NULL;head->data=1;//此處頭結點并不是虛節點tail=head;for(i=2;i<=n;i++){p=(struct node *)malloc(sizeof(struct node));p->data=i;p->next=NULL;tail->next=p;tail=p;}tail->next=head;//讓最后一個節點指向頭結點(循環鏈表建立的關鍵)return head; }; void baoshu(struct node *head)//報數過程的操作 {int num=0;//猴子報數的計數變量int count=0;//統計被殺的人的個數struct node *p,*q;q=head;while(q->next!=head)q=q->next;p=head;while(count!=n-1){num++;if(num%m==0)//數到m的人被刪{q->next=p->next;free(p);p=q->next;count++;}else{q=p;p=p->next;}}printf("%d\n",q->data); } int main() {struct node *head;scanf("%d %d",&n,&m);head=creat();baoshu(head);return 0; }轉載于:https://www.cnblogs.com/jiangyongy/p/3971603.html
總結
以上是生活随笔為你收集整理的[1197]约瑟夫问题 (循环链表)SDUT的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 封装log4cp p
- 下一篇: mile for gallon 汽车省油