본문 바로가기

Baekjoon

[Java] 백준 11866 : 요세푸스 문제 0

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

 

11866번: 요세푸스 문제 0

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 1,000)

www.acmicpc.net

 

[코드]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main11866 {
    public static void main(String[] args)  throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine(), " " );
        LinkedList<Integer> linkedList = new LinkedList<>();
        List<Integer> list = new ArrayList<>();


        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());
        int index = 0;


        for (int i = 0 ; i < N ; i++){
          linkedList.add(i+1);
        }
        
	//한 사람이 남을때 까지 반복해준다.
    //한 사람은 몇번째 사람인지 구해줄 필요가 없기때문이다. 
      while ( N > 1) {
      //index 범위가 N보다 넘어가지 않도록 하기 위함
          index = (index + (K -1)) % N; 
          list.add(linkedList.remove(index));
          N--;
      }
      //마지막 사람은 그냥 제거해준다.
        list.add(linkedList.remove());


        String str =list.toString();
        str =str.replace("[","<");
        str =str.replace("]",">");
        System.out.print(str);

    }
}

'Baekjoon' 카테고리의 다른 글

[Java] 백준 1966번 : 프린터 큐  (0) 2022.01.12
[Java] 백준 7568번 : 덩치  (0) 2022.01.10
[Java] 백준 10773번 : 제로  (0) 2022.01.10
[Java] 백준 2164 : 카드2  (0) 2022.01.07
[Java] 백준 10814번:나이순 정렬  (0) 2022.01.07