#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <string>
using namespace std;
int parent[200001];
int friendcount[200001];
int FindParent(int now)
{
if (now == parent[now])
return now;
else
return parent[now] = FindParent(parent[now]);
}
void SetParent(int now, int set)
{
int x = FindParent(now);
int y = FindParent(set);
if (x < y)
{
parent[y] = x;
friendcount[x] += friendcount[y];
}
else if (x > y)
{
parent[x] = y;
friendcount[y] += friendcount[x];
}
}
using namespace std;
int arr[100001];
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n = 0;
cin >> n;
while (n--)
{
int F = 0;
cin >> F;
for (int i = 0; i < 200001; ++i)
{
parent[i] = i;
friendcount[i] = 1;
}
int count = 0;
unordered_map<string, int> unmap = {};
for (int i = 0; i < F; ++i)
{
int friendnum1 = 0;
int friendnum2 = 0;
string s1, s2;
cin >> s1 >> s2;
if (unmap[s1])
{
friendnum1 = unmap[s1];
}
else
{
unmap[s1] = ++count;
friendnum1 = count;
}
if (unmap[s2])
{
friendnum2 = unmap[s2];
}
else
{
unmap[s2] = ++count;
friendnum2 = count;
}
SetParent(friendnum1, friendnum2);
cout << friendcount[FindParent(friendnum1)] << '\n';
}
}
return 0;
}
이름으로 본인의 순서를 찾아내고 그 숫자를 parent로 본인의 숫자로 합쳐서 찾습니다.
'오늘의 알고리즘' 카테고리의 다른 글
[C++] 백준 17472 다리 만들기 2 (0) | 2023.05.19 |
---|---|
[C++] 백준 11780 플로이드 2 (0) | 2023.05.12 |
[C++] 백준 1450 냅색문제 (0) | 2023.05.08 |
[C++] 백준 9370 미확인도착지 (0) | 2023.05.03 |
[C++] 백준 1956 운동 (0) | 2023.05.02 |