您的位置:首页 > 其它

HDU 1213 How Many Tables(并查集)

2016-03-18 11:29 465 查看
题目链接:

HDU 1213 How Many Tables

题意:

有N位朋友,如果A朋友和B朋友认识,B朋友和C朋友认识,那么A、B、C都互相认识。互相认识的朋友坐一桌。

给出m对互相认识的朋友,问最少需要多少桌?

分析:

直接对每对互相认识的朋友合并,然后逐一将每位朋友的祖先标记下(find(i)),

然后统计有多少位朋友被标记了就是需要的最少桌子数量。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
#include <cmath>
using namespace std;

const int maxn = 1010;

int pre[maxn], vis[maxn];
int T, n, m, a, b;

/*
int find(int x)
{
return pre[x] == x ? x : pre[x] = find(pre[x]);
}
*/

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

void mix(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
{
if (fy < fx) swap(fx, fy);
pre[fy] = fx;
}
}

int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
pre[i] = i;
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &a, &b);
mix(a, b);
}
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
vis[find(i)] = 1;
int ans = 0;
for (int i = 1; i <= n; i++)
ans += vis[i];
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: