作者 abc618382
单位 河北科技大学
约瑟夫环问题
约瑟夫环是一个数学的应用问题:已知n个人(以编号a,b,c...分别表示)围坐在一张圆桌周围。从编号为1的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
输入格式:
固定为2行,第一行为m,第二行为n个人的名称列表,用英文字母代表,元素直接使用英文逗号 , 分开
输出格式:
一行,为出列元素序列,元素之间使用英文逗号 , 分开【注意:末尾元素后没有逗号】
输入样例:
在这里给出一组输入。例如:
3
a,b,c,d,e,f,g
输出样例:
在这里给出相应的输出。例如:
c,f,b,g,e,a,d
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C++代码:
#include "iostream"
using namespace std;
struct Node {
//存放数字
char digt;
struct Node *next;
};
//创造链表
struct Node *createList();
//创造新的节点
struct Node *createNode(char x, struct Node *head);
//循环删除
void deleteNode(struct Node * head,int m);
int main() {
int m;
char x;
cin >> m;
getchar();
struct Node *head = createList();
while ((x = getchar()) != '\n') {
if(x != ',')
head = createNode(x, head);
}
struct Node *p = head;
while (p->next) {
p = p->next;
}
p->next = head->next;
deleteNode(head,m);
return 0;
}
struct Node *createList() {
struct Node *head = (struct Node *) malloc(sizeof(struct Node));
head->next = NULL;
return head;
}
struct Node *createNode(char x, struct Node *head) {
struct Node *p = head;
while (p->next) {
p = p->next;
}
struct Node *node = (struct Node *) malloc(sizeof(struct Node));
node->next = NULL;
node->digt = x;
p->next = node;
return head;
}
void deleteNode(struct Node* head,int m){
int k=1,count = 1;
struct Node* p = head->next;
struct Node* temp=head;
if(m == 1){
cout << p->digt;
p = p->next;
while(p != head->next){
cout << ',' << p->digt;
p = p->next;
}
return;
}
while(head->next){
if(k == m){
if(temp->next == p->next){
cout << ',' << p->digt;
return;
}
if(count == 1) {
cout << p->digt;
count++;
}
else
cout << ',' << p->digt;
temp->next = p->next;
free(p);
p = temp->next;
}else{
temp = p;
p = p->next;
}
k = k % m + 1;
}
}