您的位置:首页 > 产品设计 > UI/UE

hdu1232 畅通工程 && poj2524 Ubiquitous Religions(并查集裸)

2016-01-31 10:22 423 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1232

题意:给你n个点m条边,求再需要添加多少条边就可以变成一个连通图。

思路:并查集裸体,思路看并查集详解。

#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

typedef long long LL;

const int N = 100010;
const int INF = 0x3f3f3f3f;

int pre
, sum;

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

void Union(int p1, int p2)
{
int x = Find(p1);
int y = Find(p2);
if(x != y)
{
pre[x] = y;
sum--;
}
}

int main()
{
// freopen("in.txt", "r", stdin);
int n, m, p1, p2;
while(~scanf("%d", &n))
{
if(n == 0) break;
scanf("%d", &m);
sum = n-1;//原本的边数
for(int i = 1; i <= n; i++)
pre[i] = i;
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &p1, &p2);
Union(p1, p2);
}
printf("%d\n", sum);
}
return 0;
}

http://poj.org/problem?id=2524

题意:给你n个节点m个关系,每个关系代表两人在一个宗教,求宗教数量。

思路:刚开始连通分量,每加一条边减一个,最后即为所得。

#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

typedef long long LL;

const int N = 100010;
const int INF = 0x3f3f3f3f;

int pre
, sum;

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

void Union(int p1, int p2)
{
int x = Find(p1);
int y = Find(p2);
if(x != y)
{
pre[x] = y;
sum--;
}
}

int main()
{
// freopen("in.txt", "r", stdin);
int n, m, p1, p2, Case = 1;
while(~scanf("%d%d", &n, &m))
{
if(n == 0 && m == 0) break;
sum = n;//原本的连通分量数
for(int i = 1; i <= n; i++)
pre[i] = i;
for(int i = 1; i <= m; i++)
{
scanf("%d%d", &p1, &p2);
Union(p1, p2);
}
printf("Case %d: %d\n", Case++, sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu poj