思路: 简单并查集
分析:
1 利用map对每个人进行编号,然后利用并查集即可
2 这一题有个地方就是输入case的时候要判断不等于EOF
代码:
#include<map> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int N = 30; const int MAXN = 200003; int n; int father[MAXN]; int rank[MAXN]; map<string , int>mp; void init(){ mp.clear(); for(int i = 0 ; i < MAXN ; i++){ father[i] = i; rank[i] = 1; } } int find(int x){ if(father[x] != x){ int fa = father[x]; father[x] = find(fa); rank[x] += rank[fa]; } return father[x]; } int solve(int x , int y){ int fx = find(x); int fy = find(y); if(fx != fy){ father[fx] = fy; rank[fy] += rank[fx]; } printf("%d\n" , rank[fy]); } int main(){ int cas , cnt; int x , y; char str[N]; while(scanf("%d" , &cas) != EOF){ while(cas--){ scanf("%d" , &n); init(); cnt = 1; while(n--){ scanf("%s" , str); if(!mp[str]) mp[str] = cnt++; x = mp[str]; scanf("%s" , str); if(!mp[str]) mp[str] = cnt++; y = mp[str]; solve(x , y); } } } return 0; }