Koala - 9기/기초 알고리즘 스터디

[백준 / C++] 7785번: 회사에 있는 사람

님남누 2023. 1. 20. 23:54

문제 링크

 

7785번: 회사에 있는 사람

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

www.acmicpc.net

문제

문제 해석

이름과 출입 기록을 입력한다. 출입 기록이 enter일 경우 출근 상태, leave일 경우 퇴근 상태이다. 모든 입력이 끝났을 때 출입 기록이 enter인 사람의 이름을 사전 순의 역순으로 출력하면 되는 문제이다.


코드

#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <cstring>
#include <vector>
#include <cctype>

using namespace std;
map <string, string> member;
map <string, string, greater<string>> enter_log;

int main() {

    int N;
    string name, state;
    cin >> N;

    for (int i = 0; i < N; i++) {
        cin >> name >> state;
        member.insert({name, state});
        
        if (member.find(name) != member.end()) { //member에 있다
            if (state == "enter") {
                enter_log.insert({name, name});
            }
            else if (state == "leave") {
                enter_log.erase(name);
            }
        }
        else { //member에 없다
            if (state == "enter") {
                enter_log.insert({name, name});
            }
        }
    }

    for (auto k : enter_log) {
        cout << k.first << '\n';
    }
    
    return 0;
}

문제 풀이

처음 입력받는 사람과 상태를 member라는 첫 번째 map 컨테이너에 저장한다.

이후 입력 받았을 때, member 안에 이미 있는 이름이라면 출입 상태에 따라 두 가지로 갈라지도록 한다.

먼저 출입 상태가 enter라면 enter_log라는 두 번째 map 컨테이너에 이름을 저장한다.

그렇지 않고 leave라면 enter_log에서 해당 이름을 지워줘서 enter 상태에 있는 사람만 출력하도록 했다.

사전 순의 역순으로 출력하려고 enter_log 선언할 때 greater를 써줬다.