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;
}
思路: 简单并查集
分析:
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;
}
相关文章推荐
- hdu 3172 Virtual Friends(map)
- HDU 3172 Virtual Friends 并查集+map
- hdu 3172 virtual friends 并查集
- HDU 3172 - Virtual Friends(map+并查集)
- hdu-3172 Virtual Friends(并查集+容器)
- hdu 3172 Virtual Friends(加权并查集)
- HDU 3172 Virtual Friends (并查集)
- 并查集 HDU 3172 Virtual Friends
- hdu 3172 Virtual Friends
- 文章标题 HDU 3172 : Virtual Friends (并查集+map)
- hdu 3172 Virtual Friends(并查集+map)
- hdu 3172 Virtual Friends
- HDU 3172 Virtual Friends
- HDU 3172 Virtual Friends
- hdu 3172 Virtual Friends (并查集 + 字典树)
- hdu 3172 Virtual Friends(简单并查集)
- hdu 3172 Virtual Friends(并查集)
- HDU 3172 Virtual Friends (并查集与map的运用,同HDU1829)
- hdu 3172 Virtual Friends 【并查集+map】
- HDU 3172 Virtual Friends 带权并查集 -秩