HDU3635(并查集)

来源:互联网 发布:关于经济最优化的问题 编辑:程序博客网 时间:2024/06/04 18:41

题目大意:n个龙珠,q个操作。操作T是将第Ath所在的城市里的所有龙珠移向第Bth龙珠所在的城市;操作Q是询问第Ath龙珠所在的城市、所在城市的龙珠总数,以及第Ath龙珠被移动的次数。

#include <cstdio>#include <algorithm>#include <iostream>#include <cstring>#include <string>#include <cmath>using namespace std;const int maxn = 11111;struct node{    int fa, step, sum;}p[maxn];int n, m;void init(){    for(int i=0; i<=n; i++)    {        p[i].fa = i;        p[i].sum = 1;        p[i].step = 0;    }}int find_fa(int x){    if(x == p[x].fa)        return x;    int tot = p[x].fa;    p[x].fa = find_fa(p[x].fa);    p[x].step += p[tot].step;    return p[x].fa;}void un(int x, int y){    int fx = find_fa(x);    int fy = find_fa(y);    if(fx != fy)    {        p[fx].fa = fy;        p[fx].step++;        p[fy].sum += p[fx].sum;        p[fx].sum = 0;    }}int main(){    int T, kase = 0;    scanf("%d", &T);    while(T--)    {        scanf("%d%d", &n, &m);        init();        char op[5];        int from, to, vex;        printf("Case %d:\n", ++kase);        for(int i=0; i<m; i++)        {            scanf("%s", op);            if(op[0] == 'T')            {                scanf("%d%d", &from, &to);                un(from, to);            }            else            {                scanf("%d", &vex);                int ans = find_fa(vex);                printf("%d %d %d\n", ans, p[ans].sum, p[vex].step);            }        }    }    return 0;}


0 0
原创粉丝点击