hdu 1213 How Many Tables(并查集)

来源:互联网 发布:淘宝贪吃飒 编辑:程序博客网 时间:2024/05/20 20:58
题目链接:<a target=_blank href="http://acm.hdu.edu.cn/showproblem.php?pid=1213">http://acm.hdu.edu.cn/showproblem.php?pid=1213</a>

题       意:Ignatius有n个朋友,相互认识的可以坐到一起,问需要多少桌子。

思       路:使用并查集将数据处理好,最后计算有几个根结点(即要几张桌子)。

代码如下:

#include <iostream>using namespace std;#include <string.h>#include <stdio.h>#include <queue>#include <algorithm>typedef long long LL;int ben[1006];int findx( int x ){    int r = x;    while( r != ben[r] )        r =ben[r];    return r;}void mergex( int x, int y ){    int fx = findx(x);    int fy = findx(y);    if( fx != fy )        ben[fx]=fy;}int main(){    int T;    scanf ( "%d", &T );    while ( T-- )    {        int n, m;        scanf ( "%d %d", &n, &m );        for( int i = 0; i <= n; i++ )            ben[i]=i;        for( int i = 0; i < m; i ++ )        {            int x, y;            scanf ( "%d %d", &x, &y );            mergex(x,y);        }        int ans = 0;        for( int i = 1; i <= n; i ++ )            if( ben[i] == i ) ans++;        printf("%d\n", ans );    }    return 0;}


0 0
原创粉丝点击