백준

백준 7785 회사에 있는 사람(Java)

Park DJ 2023. 1. 22. 20:17

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

 

7785번: 회사에 있는 사람

첫째 줄에 로그에 기록된 출입 기록의 수 n이 주어진다. (2 ≤ n ≤ 106) 다음 n개의 줄에는 출입 기록이 순서대로 주어지며, 각 사람의 이름이 주어지고 "enter"나 "leave"가 주어진다. "enter"인 경우는

www.acmicpc.net


 

해석 및 팁

 


 

이 문제를 풀 때 바로 Arrays.list를 사용하면 시간초과가 발생합니다. 또한 중복도 존재하지 않으므로 Hash.set을 통해 입력받은 후 Array.list로 정렬한 후에 StringBuilder에 저장해서 출력하면 됩니다.

 


 

Java 코드

 


import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    StringBuilder sb = new StringBuilder();
    HashSet<String> set = new HashSet<>();
    
    int n = sc.nextInt();
    
    for(int i = 0; i < n; i++) {
      String name = sc.next();
      String check = sc.next();
      if(check.equals("enter")) set.add(name);
      else set.remove(name);
    }

    ArrayList<String> list = new ArrayList<>(set);

    Collections.sort(list, Collections.reverseOrder());

    for(int i = 0; i < list.size(); i++) sb.append(list.get(i)+"\n");
    
    System.out.println(sb);
  }
}