Algorithm

[Algo] 백준 20913 최애의 팀원

조핑구 2024. 7. 30. 16:21

문제 바로가기 : https://www.acmicpc.net/problem/29813

메모리 : 15760KB

시간 : 156 ms

언어 : Java 11


코드

import java.io.*;
import java.util.*;

public class Main {
    static class Node {
        String name;
        int num;

        Node(String name, int num) {
            this.name = name;
            this.num = num;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        Queue<Node> q = new LinkedList<>();
        StringTokenizer st;
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            q.add(new Node(st.nextToken(), Integer.parseInt(st.nextToken())));
        }
        Node now = q.peek();
        while (!q.isEmpty()) {
            now = q.poll();
            for (int i = 1; i < now.num; i++) { //패스해주기
                Node next = q.poll();
                q.add(next);
            }
            q.poll(); //팀원찾으면 내보내기
        }
        System.out.println(now.name);
    }
}

 

풀이

가장 앞에 있는 학생은 자신의 학번만큼의 사람을 "패스" 하고 팀원을 찾는다. 패스한 사람은 다시 뒤로 가서 줄을 선다. 바로 Queue를 떠올릴 수 있다. 큐의 머리의 짝꿍을 찾으면 된다. N은 홀수이기 때문에 모두 팀원을 찾으면 한 명이 남고, 그 남은 사람이 정답이 된다.