并查集—HDU 1213

题目点这里

题目大意:

A和B认识,那么A和B可以坐在一张桌子上,
A认识B,B认识C,那么A,B,C都可以坐在一张桌子上,桌子不限定人数

最基本的用并查集判断连通性,然后输出连通分量的个数

代码


 1. #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
const int M = 1005;
int id[M];
int count;
int find(int p)
{
    while(p != id[p])   p = id[p];
    return p;
}
bool connected(int p,int q)
{
    return find(p) == find(q);
}
void unionn(int p,int q)
{
    int pRoot = find(p);
    int qRoot = find(q);
    if(pRoot == qRoot)  return;

    id[pRoot] = qRoot;

    --count;
}
int main()
{
    int n,m;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        count = n;
        for(int i = 1;i <= n; i++)
            id[i] = i;      
        while(m--)
        {
            int p,q;
            scanf("%d%d",&p,&q);
            unionn(p,q);
        }
        printf("%d\n",count);
    }
    return 0;
 } 

代码还可以优化,带上路径压缩。
做的第一道并查集题目。

发布了48 篇原创文章 · 获赞 17 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章