zoj 3641 并查集

小树插大树,毫无技巧可言。插反了就会MLE,别问我怎么知道。

#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <queue>
#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <algorithm>
#include <vector>
using namespace std;
#define LL long long
#define CL(a, val) memset(a, val, sizeof(a))
typedef pair<int, int> PII;

int N;
char op[10];
map<string, int> name;
int idx;
int fa[100001];
set<int> pt[100001];

int getfather(int x)
{
    if(fa[x] == x)
        return x;
    return fa[x] = getfather(fa[x]);
}

void _merge(int x, int y)
{
    int fx = getfather(x), fy = getfather(y);
    if(pt[fx].size() > pt[fy].size())
        swap(fx, fy);
    fa[fx] = fy;
    set<int>::iterator it;
    for(it = pt[fx].begin(); it != pt[fx].end(); ++ it)
    {
        pt[fy].insert(*it);
    }
}

int getid(string n)
{
    if(name.find(n) == name.end())
        return name[n] = idx ++;
    else
        return name[n];
}

void arrive()
{
    char sz[100];
    scanf("%s", sz);
    string strname(sz);
    int id = getid(strname);
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++ i)
    {
        int x;
        scanf("%d", &x);
        pt[id].insert(x);
    }
}

void share()
{
    char sz0[100], sz1[100];
    scanf("%s%s", sz0, sz1);
    string sn0(sz0);
    string sn1(sz1);
    int id0 = getid(sn0), id1 = getid(sn1);
    _merge(id0, id1);
}

void check()
{
    char sz[100];
    scanf("%s", sz);
    string sn(sz);
    int id = getid(sn);
    int gid = getfather(id);
    printf("%d\n", pt[gid].size());
}

void cd_test()
{
    name.clear();
    idx = 0;
    for(int i = 0; i < 100001; ++ i)
        fa[i] = i;
    for(int i = 0; i < 100001; ++ i)
        pt[i].clear();
    for(int i = 0; i < N; ++ i)
    {
        scanf("%s", op);
        if(op[0] == 'a')
        {
            arrive();
        }
        else if(op[0] == 's')
        {
            share();
        }
        else if(op[0] == 'c')
        {
            check();
        }
    }
}

int main() 
{
#if _MSC_VER == 1700
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    while(scanf("%d", &N) != EOF)
    {
        cd_test();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值