hdu 3172 Virtual Friends

简介: 点击打开3172 思路: 简单并查集 分析: 1 利用map对每个人进行编号,然后利用并查集即可 2 这一题有个地方就是输入case的时候要判断不等于EOF 代码: #include#include#include#incl...

点击打开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[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;
}



目录
相关文章
|
4月前
|
Java
hdu-4883- (Best Coder) TIANKENG’s restaurant
hdu-4883- (Best Coder) TIANKENG’s restaurant
21 0
|
4月前
杭电2095(find your present (2))
杭电2095(find your present (2))
23 0
|
11月前
codeforces 302 B. Eugeny and Play List
题目链接 有n首歌,编号从1到n,每首歌播放时间为t,播放次数为c,n首歌按次序播放,有m个询问,输出第v分钟正在播放的歌曲编号。 很简单的二分查找,直接贴代码。
35 0
LeetCode 202. Happy Number
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
106 0
LeetCode 202. Happy Number
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
ZOJ - Problem Set - 3960 What Kind of Friends Are You?
ZOJ - Problem Set - 3960 What Kind of Friends Are You?
81 0
ZOJ - Problem Set - 3960 What Kind of Friends Are You?
|
机器学习/深度学习
LeetCode之Happy Number
LeetCode之Happy Number
140 0
|
机器学习/深度学习