ACM —— 1012 Joseph

解题代码:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner stdin = new Scanner(System.in);
		int k;
		int[] joseph = new int[14];
		while ((k = stdin.nextInt()) != 0) {
			if (joseph[k] > 0) { // 每个环值是唯一的,如果计算过,直接输出
				System.out.println(joseph[k]);
				continue;
			}
			int n = 2*k;
			int m;
			Lable:
				for(int r = 0; ;r++) {
					for (int h = k+1; h <= n; h++) {
						m = n * r + h; // 只计算余数在(k, 2k] 区间的m值
						if (Joseph(k,m,n)) {
							break Lable;
						}
					}
				}
			joseph[k] = m;
			System.out.println(m);
		}
	}

	private static boolean Joseph(int k, int m, int n) {
		int a = 1;
		for (int i = 1; i <= k; i++) {
			a = (a + m - 1)%(n - i + 1); // 约瑟夫环公式
			if (a == 0) {
				a = n - i + 1;
			} 
			if ((a<=k)&&(a>=0)) {
				return false;
			}
		}
		return true;
	}

}


 

猜你喜欢

转载自blog.csdn.net/WYYZ5/article/details/48653373