티스토리 뷰
4195번: 친구 네트워크
첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스의 첫째 줄에는 친구 관계의 수 F가 주어지며, 이 값은 100,000을 넘지 않는다. 다음 F개의 줄에는 친구 관계가 생긴 순서대로 주어진
www.acmicpc.net
백준 소스코드 [C++] 4195 친구 네트워크
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
#include <set>
#include <map>
#include <unordered_map>
#include <sstream>
#define all(v) v.begin(), v.end()
#define pii pair<int,int>
#define make_unique(v) v.erase(unique(v.begin(), v.end()), v.end())
typedef long long ll;
using namespace std;
int anc[200001], cnt[200001];
int getRoot(int x) {
if (x == anc[x]) return x;
return anc[x] = getRoot(anc[x]);
}
int merge(int L,int R) {
L = getRoot(L);
R = getRoot(R);
if (L == R) return cnt[R];
else
{
if (cnt[L] > cnt[R]) {
anc[L] = R;
cnt[R] += cnt[L];
return cnt[R];
}
else {
anc[R] = L;
cnt[L] += cnt[R];
return cnt[L];
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t, n;
cin >> t;
while (t--) {
cin >> n;
unordered_map<string, int> hash;
int chk = 0;
for (int i = 0;i < 2 * n;i++) {
anc[i] = i; cnt[i] = 1;
}
for (int i = 0;i < n;i++) {
string a, b;
cin >> a >> b;
if (hash.count(a) == 0) hash.insert({ a, chk++ });
if (hash.count(b) == 0) hash.insert({ b, chk++ });
cout << merge(hash[a], hash[b]) << '\n';
}
}
return 0;
}
'백준' 카테고리의 다른 글
백준 소스코드 [C++] 1525 퍼즐 (0) | 2021.03.07 |
---|---|
백준 소스코드 [C++] 1253 좋다 (0) | 2021.03.06 |
백준 소스코드 [C++] 11780 플로이드 2 (0) | 2021.03.06 |
백준 소스코드 [C++] 10159 저울 (0) | 2021.03.05 |
백준 소스코드 [C++] 2143 두 배열의 합 (0) | 2021.03.04 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 최단경로 문제
- 강한 순환 참조
- IOS
- 에드몬드 카프 알고리즘
- 코딩대회
- 네트워크 플로우
- CPU와 Memory
- test coverage
- 컴퓨터 추상화
- 벨만포드 알고리즘
- 최대 매칭
- observeOn
- 최단경로 알고리즘
- WWDC17
- 포드 풀커슨 알고리즘
- WWDC21
- 네트워크 유량
- Testable
- rxswift
- 부스트캠프 6기
- 다익스트라 시간복잡도
- State Restoration
- WWDC19
- 벨만포드 시간복잡도
- WWDC16
- HIG
- MeTal
- mach-o
- 최단경로문제
- CompositionalLayout
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함