@lawk97
2017-05-27T10:49:44.000000Z
字数 2244
阅读 1030
并查集
生成树
[[HDU - 1213]
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,t,ans;
int set[1005],size[1005],flag[1005];
void build(){
for (int i = 1; i <= n; ++i)
{
set[i]=i;
size[i]=1;
}
}
int f(int x){
if (x==set[x])
{
return x;
}else{
set[x]=f(set[x]);
return set[x];
}
}
void connect(int x,int y){
int fx,fy;
fx=f(x);
fy=f(y);
if (fx==fy)
{
return;
}
if (size[fx]>=size[fy])
{
size[fx]+=size[fy];
set[fy]=fx;
}else{
size[fy]+=size[fx];
set[fx]=fy;
}
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
build();
ans=0;
for (int i = 1; i <= n; ++i)
{
flag[i]=0;
}
for (int i = 1; i <= m; ++i)
{
int a,b;
scanf("%d%d",&a,&b);
connect(a,b);
}
for (int i = 1; i <= n; ++i)
{
if (flag[f(i)]==0)
{
flag[set[i]]=1;
ans++;
}
}
printf("%d\n",ans );
}
return 0;
}
[POJ - 1962]
题意
思路
[POJ - 1182]
思路
代码
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n,k,ans,set[150005],size[150005];
struct word{
int d,x,y;
}w[100005];
void build(){
for (int i = 1; i <= 3*n; ++i)
{
set[i]=i;
size[i]=1;
}
}
int f(int x){
if (x==set[x])
{
return x;
}else{
set[x]=f(set[x]);
return set[x];
}
}
void connect(int x,int y){
int fx,fy;
fx=f(x);
fy=f(y);
if (fx==fy)
{
return;
}
if (size[fx]>=size[fy])
{
size[fx]+=size[fy];
set[fy]=fx;
}else{
size[fy]+=size[fx];
set[fx]=fy;
}
}
int main(){
ans=0;
scanf("%d%d",&n,&k);
for (int i = 0; i < k; ++i)
{
scanf("%d%d%d",&w[i].d,&w[i].x,&w[i].y);
}
build();
for (int i = 0; i < k; ++i)
{
int d,x,y;
d=w[i].d;
x=w[i].x;
y=w[i].y;
if (x>n||y>n)
{
ans++;
continue;
}
if (d==2&&x==y)
{
ans++;
continue;
}
if (d==1)
{
if (f(3*x-2)==f(3*y-1)||f(3*x-1)==f(3*y)||f(3*x)==f(3*y-2)||
f(3*y-2)==f(3*x-1)||f(3*y-1)==f(3*x)||f(3*y)==f(3*x-2))
{
ans++;
continue;
}
connect(3*x-2,3*y-2);
connect(3*x-1,3*y-1);
connect(3*x,3*y);
}else{
if (f(3*x-2)==f(3*y-2)||f(3*x-1)==f(3*y-1)||f(3*x)==f(3*y))
{
ans++;
continue;
}
if (f(3*y-2)==f(3*x-1)||f(3*y-1)==f(3*x)||f(3*y)==f(3*x-2))
{
ans++;
continue;
}
connect(3*x-2,3*y-1);
connect(3*x-1,3*y);
connect(3*x,3*y-2);
}
}
printf("%d\n",ans );
return 0;
}