Where who wants to meet someone

백준 Swift [11866] 요세푸스 문제 0 본문

백준 알고리즘 문제 기록/스택, 큐, 덱

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

Lust3r 2023. 8. 25. 14:53
728x90

난이도

실버 V

 

문제

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

 

11866번: 요세푸스 문제 0

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

www.acmicpc.net

 

내 답안

let input = readLine()!.split(separator: " ").map { Int($0)! }

var queue = [Int]()
var result = [Int]()

var position = input[1]

for i in 1...input[0] {
    queue.append(i)
}

while !queue.isEmpty {
    if queue.count == 1 {
        result.append(queue.popLast()!)
        break
    }

    if position <= queue.count {
        result.append(queue[position - 1])
        queue.remove(at: position - 1)
        position += input[1] - 1
    } else {
        position -= queue.count
    }
}

print("<" + result.map { String($0) }.joined(separator: ", ") + ">")

/*
 1 2 3 4 5 6 7
 1 2 4 5 6 7 || index 2 / 3 out
 1 2 4 5 7 || index 4 / 6 out
 1 4 5 7 || index 1 / 2 out
 1 4 5 || index 3 / 7 out
 1 4 || index 2 / 5 out
 4 || index 0 / 1 out
 || index 0 / 4 out

 index 2씩 증가
 */
  • 1) 숫자를 담을 queue와 빼낸 수를 담을 result 배열을 만든다
    2) 빼내야 할 자리를 나타내는 position 프로퍼티에 초기값으로 K를 넣어준다
    3) while문을 통해 사람이 다 빠질 때까지 하기의 과정을 반복
    3-1) 만약 queue의 수가 1이라면(사람이 한 명이라면) 끝났으므로 result에 추가해주고 종료
    3-2) position이 queue의 count보다 작거나 같다면(어차피 -1 한 값을 뺄 것이므로) result에 queue의 해당 위치의 값을 더해주고 queue에서는 제거한 다음, position의 값을 K - 1 만큼 증가
    3-3) 만약 position이 queue의 count보다 크다면 인덱스 범위를 넘어섰으므로 queue의 count만큼 빼준다
    4) while문이 종료되고(queue가 다 비워지면) <> 사이에 result의 요소를 ", "로 연결하여 출력
  • 하단의 주석은 규칙을 처음에 찾아보고자 작성했던 메모..