约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围.从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列.

 

import java.util.Scanner;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int k = scanner.nextInt();
		int m = scanner.nextInt();

		// 初始化
		Node head = new Node(1, null);
		Node temp = new Node();
		for (int i = 2; i <= n; i++) {
			Node node = new Node(i, null);
			if (i == n) {
				node.node = head;
				temp.node = node;
				temp = temp.node;
			} else {
				if (head.node == null) {
					head.node = node;
					temp = node;
				} else {
					temp.node = node;
					temp = temp.node;
				}
			}
		}
		temp = head;
		for (int i = 1; i < k; i++) {
			temp = temp.node;
		}
		

		while (temp!=temp.node) {
			for(int i = 1 ; i < m-1; i++){
				temp = temp.node;
			}
			System.out.println(temp.node.n);
			temp.node = temp.node.node;
				

		}
		System.out.println(temp.n);
		scanner.close();
	}

}

class Node {
	int n;
	Node node;

	Node() {

	}

	public Node(int n, Node node) {
		this.n = n;
		this.node = node;
	}
}

  

posted on 2013-09-14 12:40  elleniou  阅读(794)  评论(1编辑  收藏  举报