您的位置:首页 > 其它

hdu 3172 Virtual Friends

2013-08-11 11:13 381 查看
点击打开3172

思路: 简单并查集

分析:

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
;
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;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: