POJ 1012 Joseph 经典约瑟夫环问题

POJ 1012 Joseph 经典约瑟夫环问题


Joseph
Time Limit: 1000MS Memory Limit: 10000K
Description

The Joseph’s problem is notoriously known. For those who are not familiar with the original problem: from among n people, numbered 1, 2, . . ., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved.

Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy.

Input

The input file consists of separate lines containing k. The last line in the input file contains 0. You can suppose that 0 < k < 14.
Output

The output file will consist of separate lines containing m corresponding to k in the input file.
Sample Input

3
4
0
Sample Output

5
30

Source

Central Europe 1995
题意:经典约瑟夫问题,不同的是现在前k个是好人,后k个是坏人,确定一个最小的m,使得在第一个好人出列之前所有的坏人都已出列

解题思路:

  1. 坏人只要清除了就行,不用管坏人的清除顺序
  2. m值至少大于k,即m>k
  3. 如果设被清除的人序号为i,则下一次清除时此人在队中的相对序号为i=(i+m-1)%n,n为队伍现在的总人数
  4. 保证i>k,就能保住除掉的是坏人
  5. 给定一个计数count,count达到k时代表坏人已清除完毕
    java代码实现:
import java.util.Scanner;

public class A_Joseph {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner inScanner =new Scanner(System.in);
		int k = 0;
		
		while (true) {
			k = inScanner.nextInt();
			if(k==0) break;
	
	    for(int m = k+1;;m++) {
			int n = 2*k;
			int i = 0;
			int count = 0;
			while (true) {
				i = (i + m - 1) % n;
				if (i

你可能感兴趣的:(Java学习笔记,Java,约瑟夫,算法)