并查集专题练习(一)POJ1611
来源:互联网 发布:chrome js秒杀 编辑:程序博客网 时间:2024/06/08 06:19
//最开始的时候..在最后直接比较father[0]和father[i]一直都没有正确
//后来改成了比较find_set(0)和find_set(i)才正确了..
//以后要注意这一点..其实这样去把每个点都更新一次..花不了多少时间的...
//但是如果有某些点没有更新到的话.直接用father就会导致错误
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
int father[33333],rank[33333],a[33333];
void make_set(int x)
{
father[x] = x;
rank[x] = 0;
}
int find_set(int x)
{
if(x != father[x])
{
father[x] = find_set(father[x]);
}
return father[x];
}
void Union(int x , int y)
{
int x1 = find_set(x);
int y1 = find_set(y);
if(x1 == y1)return;
else
{
if(rank[x1] > rank[y1])
{
father[y1] = x1;
find_set(y);
}
else
{
if(rank[x1] == rank[y1])
rank[y1]++;
father[x1] = y1;
find_set(x);
}
}
}
int main()
{
int m,n;
while(scanf("%d%d",&n,&m) && n + m != 0)
{
for(int i = 0 ; i < n ; i++)make_set(i);
for(int i = 1 ; i <= m ; i++)
{
int num;
scanf("%d",&num);
for(int j = 1 ; j <= num ; j++)
{
scanf("%d",&a[j]);
if(j != 1)
{
Union(a[j],a[j-1]);
}
}
}
int ans = 0;
int b = find_set(0);
for(int i = 0 ; i < n ; i++)
{
if(find_set(i) == b)ans++;
}
printf("%d\n",ans);
}
}
//后来改成了比较find_set(0)和find_set(i)才正确了..
//以后要注意这一点..其实这样去把每个点都更新一次..花不了多少时间的...
//但是如果有某些点没有更新到的话.直接用father就会导致错误
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
int father[33333],rank[33333],a[33333];
void make_set(int x)
{
father[x] = x;
rank[x] = 0;
}
int find_set(int x)
{
if(x != father[x])
{
father[x] = find_set(father[x]);
}
return father[x];
}
void Union(int x , int y)
{
int x1 = find_set(x);
int y1 = find_set(y);
if(x1 == y1)return;
else
{
if(rank[x1] > rank[y1])
{
father[y1] = x1;
find_set(y);
}
else
{
if(rank[x1] == rank[y1])
rank[y1]++;
father[x1] = y1;
find_set(x);
}
}
}
int main()
{
int m,n;
while(scanf("%d%d",&n,&m) && n + m != 0)
{
for(int i = 0 ; i < n ; i++)make_set(i);
for(int i = 1 ; i <= m ; i++)
{
int num;
scanf("%d",&num);
for(int j = 1 ; j <= num ; j++)
{
scanf("%d",&a[j]);
if(j != 1)
{
Union(a[j],a[j-1]);
}
}
}
int ans = 0;
int b = find_set(0);
for(int i = 0 ; i < n ; i++)
{
if(find_set(i) == b)ans++;
}
printf("%d\n",ans);
}
}
- 并查集专题练习(一)POJ1611
- POJ1611 并查集
- poj1611并查集
- POJ1611(并查集)
- poj1611 并查集
- POJ1611(并查集)
- poj1611(并查集)
- 并查集POJ1611
- poj1611并查集
- poj1611 并查集
- poj1611(并查集)
- POJ1611(并查集)
- POJ1611->并查集
- POJ1611-----并查集
- poj1611-并查集
- 并查集:poj1611
- 1poj1611(并查集)
- poj1611(简单并查集)
- finger print GUI
- ACCESS数据库ODBC访问异常的处理方法
- Java Process的问题
- C/C++的预编译和宏定义
- Mac OS X Lion 的 Sandbox 技术初探
- 并查集专题练习(一)POJ1611
- C# 类成员访问修饰符
- .Net相关书名推荐
- C# 实现窗体抖动
- winpcap教程
- 半透明溅显窗体
- 第9题 求整数的二进制表达式中1的个数
- intro to chrome addons hacking
- 重载与重写的区别,重载是否可以改变返回值类型