• Home
  • About
    • Dochoi의 소소한 코딩 모음 photo

      Dochoi의 소소한 코딩 모음

      코딩을 하면서 느낀점들을 모은 공간입니다.

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
    • AI
    • Algorithm
    • Algorithm-Test
    • Cloud
    • Docker
    • Kubernetes
    • iOS
    • Culture
  • Projects

[백준]:4195(친구 네트워크)

28 Oct 2020

Reading time ~1 minute

algorithm-test

4195(친구 네트워크)

#include <iostream>
#include <sstream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <memory.h>

using namespace std;

int fr[200003] = {0};

int find_parent(int n)
{
    int answer = n;
    while (fr[answer] != answer)
    {
        answer = fr[answer];
    }
    return fr[answer];
}

void merge(int a, int b,   unordered_map<int, vector<int>> & mv)
{
   
    mv[a].push_back(b);
    fr[b] = a;
    for (int i = 0 ; i < mv[b].size(); i++)
    {
        mv[a].push_back(mv[b][i]);
        fr[mv[b][i]] = a;
    }
    mv[b].clear();
}

int main()
{
    cin.tie();
//    cout.tie();
    ios_base::sync_with_stdio(false);
   //freopen("input", "r", stdin);
    
  
    
    int ts, n;
 
    string name11, name22;
    cin >> ts;
    while(ts--)
    {
        cin >> n;

        int str_to_idx = 1;
        unordered_map<string, int> m;
        unordered_map<int, vector<int>> mv;
        for (int i = 0; i < n; i++)
        {
            cin >> name11 >> name22;

            const string name1 = name11;
            const string name2 = name22;
            if (m[name1] == 0)
            {
                m[name1] = str_to_idx++;
                fr[str_to_idx - 1]  = str_to_idx - 1;
            }
            
            if (m[name2] == 0)
            {
                m[name2] = str_to_idx++;
                fr[str_to_idx - 1] = str_to_idx - 1;
            }
            
            int i_name1, i_name2;
            i_name1 = m[name1];
            i_name2 = m[name2];
            
            if (i_name1 > i_name2)
            {
                swap(i_name1, i_name2);
            }
            int i_name1_p = find_parent(i_name1);
            int i_name2_p = find_parent(i_name2);

            if (fr[i_name1] != fr[i_name2_p])
            {
                    merge(i_name1_p, i_name2_p, mv);
            }
            printf("%d\n", (int)mv[i_name1_p].size() + 1);
        }
    }
  
    
    return 0;
}


고찰

시간초과가 많이 발생하여 유니온파인드를 이용하여 풀어봤습니다.

시간을 단축하기 위해 string -> int로 매핑하였고, const string으로 변수를 선언하여 string이 복사되는 오버헤드를 없앴습니다.



Algorithm-TestUnionFindHash Share Tweet +1