本文共 1569 字,大约阅读时间需要 5 分钟。
约瑟夫问题
Time Limit: 1000 ms Memory Limit: 65536 KiBProblem Description
n个人想玩残酷的死亡游戏,游戏规则如下:n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。
请输出最后一个人的编号。
Input 输入n和m值。 Output 输出胜利者的编号。 Sample Input 5 3 Sample Output 4 Hint 第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀代码如下:
#include#include struct list{ int shu; struct list *next;};int main(){ struct list *head,*p,*q; int m,n,i; head=(struct list *)malloc(sizeof(struct list)); head->next=NULL; q=head; scanf("%d%d",&n,&m); for(i=1; i<=n-1; i++) { p=(struct list*)malloc(sizeof(struct list)); p->shu=i+1; p->next=NULL; q->next=p; q=p; } q->next=head; head->shu=1; p=head; n--; while(n--) { for(i=0; i next; p->next=p->next->next; p=p->next ; } printf("%d",p->shu); return 0;}
相隔一个月再次回头做这道题,思路大体一样;上新代码:
#include#include struct node{ int data; struct node*next;};int main(){ int i,n,m,j; struct node *head,*p,*tail; head=(struct node*)malloc(sizeof(struct node)); head->next=NULL; tail=head; scanf("%d%d",&n,&m); for(i=1; i<=n; i++) { p=(struct node*)malloc(sizeof(struct node)); p->data=i; tail->next=p; p->next=NULL; tail=p; }//进行编号 tail->next=head->next; p=head->next;//让单链表环化 for(i=1; i<=n; i++)//删N个人 { for(j=1; j<=m-2; j++) { p=p->next; } p->next=p->next->next; p=p->next; } printf("%d",p->data); return 0;}
转载地址:http://kzhwi.baihongyu.com/