在网络社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,假定 A 和 B 是朋友,B 和 C 是朋友,那么 A 和 C 也会成为朋友。即,我们规定朋友的朋友也是朋友。
现在要求你每当有一对新的朋友认识的时候,你需要计算两人的朋友圈合并以后的大小。
先输入数字n
再输入n对人名
就比并查集多了一个大小,这个大小用另一个并查集保存一下就行,合并的时候注意将两个集合合并,合并的时候不用两个都增加值,只增加一个,也就是根节点的就行。
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <cctype>
#include <map>
int father[10001];
int sizee[10001];
int get(int x){
if (father[x] == x) {
return x;
}
return father[x] = get(father[x]);
}
void mergee(int x, int y){
x = get(x);
y = get(y);
if (x != y) {
father[y] = x;
sizee[x] += sizee[y];
}
}
using namespace std;
int main(){
ios::sync_with_stdio(false);
map<string, int> m;
int n, id = 1;
cin >> n;
string x, y;
for (int i = 0; i < n; i++) {
cin >> x >> y;
if (!m.count(x)) {
m[x] = id;
sizee[m[x]] = 1;
father[m[x]] = id;
id++;
}
if (!m.count(y)) {
m[y] = id;
sizee[m[y]] = 1;
father[m[y]] = id;
id++;
}
mergee(m[x], m[y]);
cout << sizee[get(m[x])] << endl;
}
return 0;
}