标题: | 约瑟夫环 |
时 限: | 500 ms |
内存限制: | 2000 K |
总时限: | 3000 ms |
描述: |
约瑟夫环
编号为1,2,3,……,n的n个人按顺时针方向围坐一圈。任选一个正整数作为报数上限m,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数。报m的人出列,从他在顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有人全部出列为止。设计程序输出出列顺序。
|
输入: |
人数n 报数上限m
人员记录1 (格式为:姓名 学号 性别 年龄 班级 健康状况)
人员记录2
…
人员记录n |
输出: |
第1次报数出列的人员记录
第2次报数出列的人员记录
…
第n次报数出列的人员记录 |
#include <iostream>
using namespace std;
typedef struct _Node
{
string name;
string no;
string gender;
int age;
string classno;
string health;
struct _Node *Next;
}Node;
int getinfo(Node *stu)
{
cin>>stu->name;
cin>>stu->no;
cin>>stu->gender;
cin>>stu->age;
cin>>stu->classno;
cin>>stu->health;
return 0;
}
int printinfo(Node *stu)
{
cout<<stu->name<<" "<<stu->no<<" "<<stu->gender<<" "<<stu->age<<" "<<stu->classno<<" "<<stu->health<<endl;
return 0;
}
int main()
{
int totalnum, upno;
string _name;
cin>>totalnum>>upno;
//creat head node
Node *head,*s,*p,*q;
head=new Node;
getinfo(head);
p=head;
p->Next=p;
//insert other node
for (int i=2;i<=totalnum;i++)
{
s=new Node;
getinfo(s);
s->Next=p->Next;
p->Next=s;
p=p->Next;
}
p=q=head;
int currno=totalnum;
while(currno!=1)
{
for(int j=1;j<upno;j++)
{
p=p->Next;//p direct the node to be deleted
}
printinfo(p);
while(q->Next!=p)
{
q=q->Next;//q is the pre node of p
}
//delete p
q->Next=p->Next;
//store p
s=p;
//move p to the next position
p=p->Next;
delete(s);
currno--;
}
printinfo(p);
delete(p);
//printinfo(head);
return 0;
}