poj1012:约瑟夫问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gods_magic/article/details/53680323
import java.util.Scanner;

public class Main {
	static int[] Result = new int[13];

	public static void main(String[] args)  {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			int K = in.nextInt();
			if (K == 0) {
				return;
			}
			// 没有这个if,会超时
			if (Result[K - 1] != 0) {
				System.out.println(Result[K - 1]);
				continue;
			}
			getminM(K);
			System.out.println(Result[K - 1]);
		}

	}

	// 测试M是否符合
	public static void getminM(int K) {
		int M;
		// M没有上限,初始的M值至少为K+1,否则会不符合要求
		for (M = K + 1;; M++) {
			if (test(K, M)) {
				Result[K - 1] = M;
				break;
			}
		}
	}

	// 打表
	//如果
	public static boolean test(int K, int M) {
		boolean isFlag = true;
		int i, t = 0;
		// temp为当前环中的总人数
		int temp = 2 * K;
		for (i = 1; i <= K; i++) {
			// 公式
			t = (t + M - 1) % temp;
			// 环中的人数减少1
			temp--;
			if (t < K) {
				// 如果说初出局的编号在前K个,此时M不符合要求
				isFlag = false;
				return isFlag;
			}
		}
		return isFlag;
	}

}

猜你喜欢

转载自blog.csdn.net/Gods_magic/article/details/53680323