poj 3908 还是能力不够,总得看别人代码后才幡然醒悟!

并查集算法详解
本文深入探讨了并查集算法的实现原理及其在解决特定类型问题中的应用。通过具体的代码示例介绍了如何使用并查集进行元素的合并及查找操作,并展示了如何通过删除元素来维护并查集的状态。

OJ

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <list>
#include <queue>
#include <stack>
#include <cmath>

using namespace std;

#define PF(x) (scanf("%d",&x))
#define PT(x,y) (scanf("%d%d",&x,&y))
#define PR(x) (printf("%d\n",x))
#define PRT(x,y)(printf("%d %d\n",x,y))
#define PB(x)(scanf("%I64d",&x))
#define PRB(x)(printf("%I64d\n",(x)))
typedef __int64 LL;
#define N 100005
#define M 105
#define Mod 1000
#define Inf 0x7fffffff

int ar[N];
int f[N];
int n;

int find(int r)
{
	if(ar[r] == r) return r;
	int t = find(ar[r]);
	ar[r] = t;
	return t;
}
void uns(int a,int b)
{
	ar[a] = b;
}
void del(int a)
{
	f[a] = ++n;
	ar[n] = n;
}
void init()
{
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<=n;i++)
			ar[i] = f[i] = i;
		int ans1 = 0,ans2 = 0;

		char s[10];
		int a,b;
		while(true)
		{
			scanf("%s",s);
			if(s[0] == 'e') break;
			else if(s[0] == 'c') 
			{
				int x,y;
				PT(x,y);
				a = find(f[x]);
				b = find(f[y]);
				uns(a,b);
			}
			else if(s[0]=='q')
			{
				int x,y;
				PT(x,y);
				a = find(f[x]);
				b = find(f[y]);
				if(a==b) ans1++;
				else ans2++;
			}
			else
			{
				int x;
				PF(x);
				del(x);
			}
		}
		printf("%d , %d\n",ans1,ans2);
	}
	return ;
}

int main()
{
	init();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值