7-2 约瑟夫环问题-hebust (25 分)

约瑟夫环问题

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

输入格式:

固定为2行,第一行为m,第二行为n个人的名称列表,用英文字母代表,元素直接使用英文逗号 , 分开

输出格式:

一行,为出列元素序列,元素之间使用英文逗号 , 分开【注意:末尾元素后没有逗号】

输入样例:

在这里给出一组输入。例如:

3
a,b,c,d,e,f,g

输出样例:

在这里给出相应的输出。例如:

c,f,b,g,e,a,d

参考答案

import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		
		int m = cin.nextInt();
		cin.nextLine();
		String str = cin.nextLine();
		String []str_t = str.split(",");
		
		List arrayList = new ArrayList<String>();
		
		for(int i = 0; i < str_t.length; i ++ ) {
			arrayList.add(str_t[i]);
		}
		
		int t = 0;
		while( arrayList.size() > 0 ) {
			Iterator It = arrayList.iterator();
			
			while( It.hasNext() ) {
				String ss = (String) It.next();
				
				if( t == m - 1 ) {
					if( arrayList.size() > 1) {
						System.out.print(ss + ",");
					}
					else {
						System.out.println(ss);
					}
					It.remove();
				}
				t = ( t + 1) % m;
			}	
		}
		
		cin.close();
	}
}