WalkerJei's Lifelog

백준알고리즘 7785번 회사에 있는 사람 C# 본문

소프트웨어 개발/코딩테스트(기성 문제)

백준알고리즘 7785번 회사에 있는 사람 C#

WalkerJei 2025. 4. 15. 21:14

세부 정보

  • 사이트: 백준알고리즘
  • 번호: 7785
  • 문제명: 회사에 있는 사람
  • 언어: C#
  • 분류: 자료 구조, 해시를 사용한 집합과 맵
  • 비고: 

 

문제

You are working in a ”Giigle” software company. The job in this company is very easy, so people don’t sit in the office from 9am till 6pm. They come to work at any time, and leave the office at any time. You have a magnetic keys system that keeps the log on all people – when they entered the office, and when they leaved. Your task is to find all people that are in office now.

 

입력

The first line of the input file contains n — the number of lines in input file (2 ≤ n ≤ 106). Each of the following n lines contain person name and word ”enter” if this person is entered, and ”leave” otherwise.

 

출력

Output names of all people that are in office now in anti-lexicographical order.

 

풀이

HashSet<>을 사용해서 풀어야 한다.

using System.Text;

StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

StringBuilder sb = new StringBuilder(5);
// 회사에 있는 직원 목록
HashSet<string> employees = new HashSet<string>();
// 출입 기록의 수
int n = Convert.ToInt32(sr.ReadLine());

for (int i = 0; i < n; i++)
{
    char input;
    
    while ((input = (char)sr.Read()) != ' ')
        sb.Append(input);

    var temp = sb.ToString();

    // leave 입력 감지 시 해당 직원을 HashSet에서 뺀다
    if(sr.Read() =='l')
        employees.Remove(temp);
    // 그 외에는 해당 직원을 HashSet에 추가한다
    else employees.Add(temp);
    // StringBuilder의 내용을 모두 지운다
    sb.Clear();
    sr.ReadLine();
}

// 직원 이름을 사전 역순으로 출력
foreach(string nameList in employees.OrderByDescending(x => x))
    sw.WriteLine(nameList);

sw.Flush();

sr.Close();
sw.Close();

 

후기

처음 문제를 보고 어떤 자료구조를 적용해야 중간에 있는 내용에 접근을 해 지우는 등의 활동을 할 수 있는 지 확인해야 겠다는 생각을 했다. 그래서 아래 소스 코드와 같이 List 자료 구조를 사용했다.

StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

// 회사에 있는 직원 목록
List<string> employees = new List<string>();
// 출입 기록의 수
int n = Convert.ToInt32(sr.ReadLine());

for (int i = 0; i < n; i++)
{
    // 출입 기록 입력
    string[] input = sr.ReadLine().Split();

    // enter 입력 시 회사에 들어갔음
    if (input[1] == "enter")
        employees.Add(input[0]);
    // leave 입력 시 회사에서 나갔음
    if(input[1] == "leave")
        employees.Remove(input[0]);
}

// 직원 이름을 사전 순의 역순으로 정렬
employees.OrderDescending();

for (int i = 0; i < employees.Count; i++)
    sw.WriteLine(employees[i]);

sr.Close();
sw.Close();

 

우여곡절 끝에 직원 이름을 OrderDescending() 함수를 사용하면 사전 순서의 역순으로 정리할 수 있다고 해서 적용해 보았고 작성을 한 곳인 Visual Studio에서는 정상적으로 작동했다. 하지만 백준알고리즘에 제출하니까 컴파일 에러만 났다. 문제를 해결하고 난 이후에 알고리즘 분류에서 해시를 사용한 집합과 맵이라는 내용이 있다면 무조건 Hash가 들어가는 자료구조를 활용해야 문제를 풀 수 있다고 생각했다.