[백준 26069번 C/C++] 붙임성 좋은 총총이

 

 

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

 

26069번: 붙임성 좋은 총총이

첫번째 줄에는 사람들이 만난 기록의 수 $N\ (1 \le N \le 1\ 000)$이 주어진다. 두번째 줄부터 $N$개의 줄에 걸쳐 사람들이 만난 기록이 주어진다. $i + 1$번째 줄에는 $i$번째로 만난 사람들의 이름 $A_i$

www.acmicpc.net


 

 

해결전략

 

map

 

map은

key와 value를 가지는데 

key값을 검색할 수 있기 때문에 다른 자료형보다 검색이 편리하다.   

 

if (myMap.find("KeyName") != myMap.end()) 

으로 검색하면 된다. 

 

map은 중복을 허용하지 않는다. 이 문제처럼 사람 이름에 중복이 없다면, key가 중복되면 데이터 삽입(=insert)이 되지않는 map을 사용하면 편하다.

 


 

코드

 

#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);

    int n;
    cin >> n;
    map<string, bool> myMap;

    string input1, input2;
    for(int i=0; i<n; i++){
        cin >> input1 >> input2;
        
        if(input1 == "ChongChong" || input2 == "ChongChong"){
            myMap.insert({ input1, true });
            myMap.insert({ input2, true });
        }

        if (myMap.find(input1) != myMap.end())
            myMap.insert({ input2, true });

        if (myMap.find(input2) != myMap.end())
            myMap.insert({ input1, true });
    }

    //디버깅
    //for (const auto& i : myMap)
    //    cout << i.first << " " << i.second << "\n";

    cout << myMap.size();

    return 0;
}

 

 


 

map 관련 참고

 

https://life-with-coding.tistory.com/305