对并查集的一点点想法..

来源:互联网 发布:软件退税流程图 编辑:程序博客网 时间:2024/05/16 13:03

最近我遇到了这样一个问题: 有n个黑社会的分别属于两个不同的帮派,狗狗帮和猪猪帮。 你将得到m条信息:
(1) D a b 表示小a和小b不在一个帮派。
(2) A a b 询问小a和小b是否在一个帮派 。

样例输入:
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4
样例输出:
不确定是否在一个帮派。
在不同的帮派。
在一个帮派。
题意分析: 这道题是对元素间关系的动态建立和询问,可以用并查集写。 我们只需要维护一棵树的根节点和各个结点的关系就好了。。 以后再解释我要睡觉了==。

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <map>#define N (10000+10)using namespace std;int f[N],book[N];int find_x(int x);void make(char ch,int a,int b);int main(){    int t,n,m,i,j;    scanf("%d",&t);    while(t--)    {        char ch; int a,b;        scanf("%d%d",&n,&m);        for(i=1; i<=n; i++)        {            f[i] = i; book[i] = 0;        }        while(m--)        {            scanf(" %c%d%d",&ch,&a,&b);            make(ch,a,b);        }    }    return 0;}int find_x(int x){    if(f[x] == x) return x;    int t = f[x];    f[x] = find_x(f[x]);    book[x] = (book[x]+book[t])%2;    return f[x];}void make(char ch,int a,int b){    int x = find_x(a);    int y = find_x(b);    if(x == y)    {        if(ch == 'D') return ;        if(book[a] == book[b])            printf("一个阵营的\n");        else            printf("不是一个阵营的\n");    }    else    {        if(ch == 'A')        {            printf("不确定他俩是不是一个阵营的\n"); return ;        }        f[x] = y;        if((book[a]+book[2]%2 == 0))            book[x] = 1;    }}
0 0