题目描述
解题思路
题目大意:
每次输入两个人A、B,代表两人成为朋友,那么两人所在的圈子将合并成一个新的圈子,输出这个新圈子的人数。
用字典树给名字分配编号,然后用并查集维护集合(圈子)关系即可。
参考代码
//**********************************************
// Author: @xmzyt1996
// Date: 2015-10-16
// Name: HDU 3172.cpp
//**********************************************
#include <cstdio>
#include <cmath>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
#include <vector>
#include <stack>
#include <queue>
#include <map>
using namespace std;
#define clr(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i < b; ++i)
#define per(i, a, b) for(int i = a; i >= b; --i)
#define pt(x) cout << #x << " = " << x << endl
#define ps puts("debug~~")
#define all(x) (x).begin(),(x).end()
#define mp make_pair
#define pb push_back
typedef __int64 ll;
typedef pair<int, int> pii;
const double pi = acos(-1.0);
const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int MAX_N = 100010;
struct Trie {
int next[60], id;
} node[MAX_N];
int par[MAX_N << 1], rak[MAX_N << 1]; // par表示父节点,rak表示所在集合的大小
int num, idx;
int getid (char c) {return c - 'A';}
void init (int n) {
num = idx = 0; // Trie初始化
clr(node, 0);
rep(i, 0, 2*n) { // 并查集初始化
par[i] = i;
rak[i] = 1;
}
}
int find (int x) {
return par[x] == x ? x : par[x] = find(par[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return ; // 在同一个集合则不合并
par[y] = x; // 将y所在的集合合并到x中
rak[x] += rak[y]; // y中人数加到x中
}
int search (char* s) {
Trie* head = &node[0];
while (*s) {
int id = getid(*s++);
if ((head->next[id]) == NULL)
head->next[id] = &node[++num];
head = head->next[id];
}
if ((head->id) == 0) (head->id) = (++idx);
// 给字符串分配编号
return head->id;
}
char name1[25], name2[25];
int main() {
int T, n;
while (~scanf("%d", &T)) {
rep(i, 0, T) {
scanf("%d", &n);
init(n);
rep(j, 0, n) {
scanf("%s %s", name1, name2);
int id1 = find(search(name1));
int id2 = find(search(name2));
unite(id1, id2);
printf("%d\n", rak[id1]);
}
}
}
return 0;
}