Iyoungman Back-end Developer

BOJ 1158. 요세푸스 문제

2020-05-06

Problem

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


Think

  • 시간복잡도를 생각해봤을때 (1 ≤ K ≤ N ≤ 5,000)
  • 단순 반복을 통해 쉽게 구현할 수 있을것 같다.
  • 이미 삭제된 인원인지 체크만 잘 해주면 될것 같다.


Solved Code

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

    private static boolean[] isRemove;

    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();//인원수
        int k = scanner.nextInt();//순서
        isRemove = new boolean[n + 1];

        List<Integer> results = new ArrayList<>();
        int current = 0;
        int tempCount = 0;
        while (results.size() < n) {
            current = getNext(current, n);

            if (!isRemove[current]) {
                tempCount++;
            }

            if (tempCount == k) {
                isRemove[current] = true;
                results.add(current);
                tempCount = 0;
            }
        }

        System.out.println(getResult(results));
    }

    private static int getNext(int current, int n) {
        return (current + 1 > n) ? 1 : current + 1;
    }

    private static String getResult(List<Integer> results) {
        StringBuilder sb = new StringBuilder();
        sb.append("<");

        String result = results.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(", "));

        sb.append(result);
        sb.append(">");

        return sb.toString();
    }
}  

Comments

Content