Boj4195 친구네트워크

Published: by Creative Commons Licence

#include<iostream>
#include<map>
using namespace std;
int root[2000001];
int counter[2000001];
int find(int k) {
	if (k == root[k]) return k;
	return root[k] = find(root[k]);
}
int merge(int p, int q) {
	p = find(p);
	q = find(q);
	if (p != q) {
		root[q] = p;
		counter[p] += counter[q];
		counter[q] = 1;
	}
	return counter[p];
}
int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		int n, idx1, idx2, num = 1;
		scanf("%d", &n);
		for (int i = 1; i <= 2 * n; ++i) {
			root[i] = i;
			counter[i] = 1;
		}
		map<string, int> index;
		char s[21], p[21];
		for (int i = 0; i < n; i++) {
			scanf("%s %s", s, p);
			if (index.count(s) == 0) index[s] = num++;
			idx1 = index[s];
			if (index.count(p) == 0) index[p] = num++;
			idx2 = index[p];
			printf("%d\n", merge(idx1, idx2));
		}
	}
}