https://www.acmicpc.net/problem/4195
4195번: 친구 네트워크
첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스의 첫째 줄에는 친구 관계의 수 F가 주어지며, 이 값은 100,000을 넘지 않는다. 다음 F개의 줄에는 친구 관계가 생긴 순서대로 주어진
www.acmicpc.net
과정
- par배열과 idx매핑, idx부여 cnt 초기화
- 입력받은 이름 값을 idx에 매핑하여 저장
- 이름 값이 idx에 없으면 새로운 idx를 부여
- 이후 weigted union find 진행
주의할 점
친구관계는 최대 10만개이므로 par배열의 최대 사이즈를 20만보다 크게 잡아야 한다.
코드
더보기
#include<string>
#include<iostream>
#include<map>
using namespace std;
int T;
int F;
map<string,int> idx;
int par[200002];
int cnt;
void init(){
for(int i=0;i<200002;i++)
par[i]=-1;
idx.clear();
cnt=0;
}
int find(int x){
if(par[x] < 0)
return x;
return par[x] = find(par[x]);
}
int union_sn(int a, int b){
a = find(a);
b = find(b);
if(a==b)
return -1*par[a];
else if(a < b){
par[a]+=par[b];
par[b]=a;
return -1*par[a];
}
else{
par[b]+=par[a];
par[a]=b;
return -1*par[b];
}
}
void solution(){
init();
cin>>F;
string a,b;
int node1, node2;
while(F--){
cin>>a>>b;
if(idx.find(a)==idx.end())
idx[a]=cnt++;
if(idx.find(b)==idx.end())
idx[b]=cnt++;
node1=idx[a];
node2=idx[b];
cout<<union_sn(node1,node2)<<'\n';
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>T;
while(T--){
solution();
}
return 0;
}

728x90
'알고리즘 > 백준 문제' 카테고리의 다른 글
| [ALGORITHM] 백준 18185 - 라면 사기(Small) (0) | 2022.10.17 |
|---|---|
| [ALGORITHM] 백준 1965 - 상자넣기 (1) | 2022.10.13 |
| [ALGORITHM] 백준 1717 - 집합의 표현 (Weighted Union Find) (0) | 2022.10.07 |
| [ALGORITHM] 백준 10875 - 뱀 (0) | 2022.10.06 |
| [ALGORITHM] 10037 - Decorating the Pastures (0) | 2022.10.03 |
댓글