ZOJ 2833-Friendship

ZOJ 2833-Friendship

题目分类:并查集

题目大意: a和b是朋友,a和c是朋友,则b和c也成为朋友
M a b 为朋友,Q x 时,问x的朋友有几个
初始大家的朋友数为1.

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int fa[200010];
int ranks[200010]; 
void initialise(int n)
{
    for (int i = 1; i <= n; i++)
        fa[i] = i,ranks[i] = 1; 
}
int getfather(int v)            
{
    return (fa[v] == v) ? v : fa[v] = getfather(fa[v]);
}

int main(){
    int n,m;
    int cnt = 1;
    int ok = 0;
    while (scanf("%d%d",&n,&m) != EOF)
    {
        if (n && m && ok)
            cout << endl;
        ok = 1;
        memset(fa,0,sizeof(fa));
        memset(ranks,0,sizeof(ranks));
        printf("Case %d:\n",cnt); 
        initialise(n);
        for (int i = 0; i < m; i++)
        {
            char ch;
            getchar();
            scanf("%c",&ch);
            if (ch == 'M')
            {
                int a,b;
                scanf("%d%d",&a,&b);
                a = getfather(a);
                b = getfather(b);
                if (a != b)
                    fa[a] = b,ranks[b] += ranks[a];
            }
            if (ch == 'Q')
            {
                int a;
                scanf("%d",&a);
                a = getfather(fa[a]);
                cout << ranks[a] << endl;
            }       
        }
        cnt++;
    }
    return 0;
}

你可能感兴趣的:(并查集,ZOJ-2833)