约瑟夫环问题

6 篇文章 0 订阅
4 篇文章 0 订阅

网上说法很多。。这里简单描述一下。

一群人围成一个圈,每个人都有自己的密钥。。出列后用其密钥做下一个循环出队数。

源代码

#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
	int ord;//order 
	int key;//key
	struct _node* next;
}Node,*pNode;
pNode Create(){
	int k,o=1;
	pNode head,cur,h;
	if(scanf("%d",&k),k){
		head=h=cur=(pNode)malloc(sizeof(Node));
		h->ord=o++;
		h->key=k;
		h->next=NULL;
	}else{
		return NULL;
	}
	while(scanf("%d",&k),k){
		cur=(pNode)malloc(sizeof(Node));
		cur->ord=o++;
		cur->key=k;
		cur->next=NULL;
		h->next=cur;
		h=cur;
	}
	h->next=head;
	return head;
}
void joh(pNode head,int start,int m){
	pNode h=head,tem;
	int count=1;
	while(h->next->ord!=start){
		h=h->next;
	}
	while(h->next){
		while(count<m){
			h=h->next;
			++count;
		}
		if(count==m){
			m=h->next->key;
                        printf("ord=%d,key=%d\n",h->next->ord,h->next->key);  //供测试用
                        tem=h->next;
			h->next=h->next->next;
			free(tem);
			count=1;
		}
		if(h==h->next){
			printf("ord=%d,key=%d\n",h->next->ord,h->next->key);
			free(h);
			break;
		}

	}
}
void show(pNode head){
	pNode h=head;
	while(h){
		printf("ord=%d,key=%d\n",h->ord,h->key);
		h=h->next;
		if(h==head){
			break;
		}
	}
}
int main(){
	pNode head=Create();
	show(head);
	printf("\n\n");
	joh(head,3,3);
	return 0;
}

测试数据

ord=1,key=2
ord=2,key=3
ord=3,key=4
ord=4,key=2
ord=5,key=5
ord=6,key=3
ord=7,key=2
ord=8,key=4
ord=9,key=3
ord=10,key=4
ord=11,key=2
ord=12,key=3
ord=13,key=2


ord=5,key=5
ord=10,key=4
ord=1,key=2
ord=3,key=4
ord=8,key=4
ord=13,key=2
ord=4,key=2
ord=7,key=2
ord=11,key=2
ord=2,key=3
ord=12,key=3
ord=6,key=3
ord=9,key=3



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值