BJ1158 요세푸스 문제

https://www.acmicpc.net/problem/1158

문제를 이해하고, 큐를 이용해 구현하면 된다.

연결리스트를 큐처럼 활용하여 구현했다.

package day0210;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class Josepus {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		st = new StringTokenizer(br.readLine(), " ");
		int N = Integer.parseInt(st.nextToken());
		int K = Integer.parseInt(st.nextToken());

		LinkedList<Integer> LL_input = new LinkedList<>();
		LinkedList<Integer> LL_output = new LinkedList<>();

		for (int i = 1; i <= N; i++) {
			LL_input.offer(i);
		}
		int idx = -1;
		for (int i = 0; i < N; i++) {
			idx += K;
			if (idx >= LL_input.size()) {
				idx = idx % LL_input.size();
			}
			LL_output.offer(LL_input.get(idx));
			LL_input.remove(idx);
			idx--;
			if (idx >= LL_input.size()) {
				idx = idx % LL_input.size();
			}
		}
		//System.out.println(LL_output);
		bw.append("<");
		for (int i = 0; i < N - 1; i++) {
			bw.append(LL_output.get(i) + ", ");
		}
		bw.append(LL_output.get(N-1) + ">");
		bw.flush();
		bw.close();

	}
}

좋은 웹페이지 즐겨찾기