hdu1213 How Many Tables

来源:互联网 发布:雅思7分有多难 知乎 编辑:程序博客网 时间:2024/05/20 20:47
#include <stdio.h>
#include <cstdio>
#include <string.h>
#include <cstring>


using namespace std;


const int N = 1000;


int pre[N];


int findd(int x)
{
    int r = x;
    while(r != pre[r])
        r = pre[r];
    int i = x, j;
    if(i != r)
    {
        j = pre[i];
        pre[i] = r;
        i = j;
    }
    return r;
}


int main()
{
   // freopen("in.txt", "r", stdin);
    int i, N, M, p1, p2, f1, f2, total, num;
    scanf("%d", &num);
    while(num --)
    {
        scanf("%d%d", &N, &M);
        total = N;
        for(i = 1; i <= N; i ++)
            pre[i] = i;
        while(M --)
        {
            scanf("%d%d", &p1, &p2);
            f1 = findd(p1);
            f2 = findd(p2);
            if(f1 != f2)
            {
                pre[f2] = f1;
                total --;
            }
        }
        printf("%d\n", total);
    }
    return 0;

}

心得:并查集水

0 0
原创粉丝点击