Josephus问题是下面的游戏 N个人从1到N编号 围成一个圈 经过M次传递后拿着热土豆的人被清除离座

数据结构与算法分析——c语言描述 练习3.10 答案


N%M,二是大于n/2可以逆向传,想不懂不写这个


#include"doubleList.h"
#include

struct  Node {
	ElementType Element;
	Position Next;
	Position Prev;
};

int isLeftOne(DoubleList dl) {
	if (!IsEmpty(dl))
		return Advance(First(dl)) == NULL;
	return 0;
}


int main() {
	int N, M;
	Position p, temp;
	DoubleList dl = CreatList();
	p = dl;
	scanf("%d%d", &N, &M);
	M = M % N;

	for (int i = 1; i <= N; i++) {
		Insert(i, p);
		p = Advance(p);
	}
	p = First(dl);
	while (!isLeftOne(dl)) {
		for (int i = 0; i < M; i++) {
			p = Advance(p);
			if (p == NULL)
				p = First(dl);
		}
		temp = Advance(p);
		if (temp == NULL)
			temp = First(dl);
		Delete_Position(p);
		p = temp;
	}
	printf("%d", Retrieve(First(dl)));
}



你可能感兴趣的:(Josephus问题是下面的游戏 N个人从1到N编号 围成一个圈 经过M次传递后拿着热土豆的人被清除离座)