约瑟夫问题(循环链表)
2015-06-07 19:14
363 查看
约瑟夫问题
Time Limit: 1000MS Memory limit: 65536K
题目描述
n个人想玩残酷的死亡游戏,游戏规则如下:n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。
请输出最后一个人的编号。
输入
输入n和m值。输出
输出胜利者的编号。示例输入
5 3
示例输出
4
提示
第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀#include<stdio.h> #include<stdlib.h> struct nobe { int data; struct nobe*next; }*p,*q,*head,*tail; int main() { int n,m,i; scanf("%d%d",&n,&m); head=(struct nobe*)malloc (sizeof(struct nobe )); p=head; p->data=1; p->next=NULL; tail=p; for(i=2;i<=n;i++) { p=(struct nobe*)malloc(sizeof(struct nobe)); p->next=NULL; p->data=i; tail->next=p; tail=p; } tail->next=head; int num=0; int count=0; p=head; while(p->next!=head) { p=p->next; } while(count <n) { q=p->next; num++; if(num%m==0) { p->next=q->next; count++; } else p=q; } printf("%d\n",p->data); return 0; }
<pre name="code" class="cpp">#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<queue> using namespace std; struct node { int data; node *next; }*head,*p,*tail,*q; int main() { int n,m,i,j; scanf("%d%d",&n,&m); head=new node; head->next=NULL; tail=head; head->data=1; for(i=2;i<=n;i++) { p=new node; p->next=NULL; p->data=i; tail->next=p; tail=p; } tail->next=head; // printf("%d\n",tail->next->data); int num=0,num1=1; p=head; //<span id="transmark"></span> while(num<n) { if(num1%m==0) { tail->next=p->next; p=tail->next; num1++; num++; } else { tail=tail->next; p=p->next; num1++; } } printf("%d\n",p->data); }
相关文章推荐
- 不敢死队问题 (循环链表)
- 【VB.NET机房重构】DataGridView数据显示
- GitHub 使用手册 - 基础篇
- 什么信息(新闻)值得关注
- fullcalendar日历控件集合知识
- 类模板相互引用的问题(错误:缺少类型说明符-假定为int。注意:C++不支持默认int)
- Spark + Hadoop-2.2.0 伪分布环境下的环境搭建
- A. Exam
- Leetcode Note: Linked List Easy Section Part 2
- 分布式系统设计原理与方案
- jQuery中html()、val()、text()的区别; javascript中innerHTMl、innerText、outHTML的区别
- Java常用类库
- 使用PythonCharm简易安装python统计包及UnicodeDecodeError,numpy.distutils.systeminfo.blas/lapacknotfounderror
- struts2+jQuery+ajax调用演示
- chapter11test5
- 面试失败的原因有哪些?
- 如何利用CSS把网页整体变成黑白灰度的
- h264: mp4 to annexb in ffmpeg
- 有序链表的归并
- Java for LeetCode 204 Count Primes