首页 > 其他 > 详细

并查集(图论) LA 3644 X-Plosives

时间:2015-12-07 20:16:18      阅读:261      评论:0      收藏:0      [点我收藏+]

 

题目传送门

题意:训练指南P191

分析:本题特殊,n个物品,n种元素则会爆炸,可以转移到图论里的n个点,连一条边表示u,v元素放在一起,如果不出现环,一定是n点,n-1条边,所以如果两个元素在同一个集合就会爆炸.

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 5;
struct DSU	{
	int rt[N], rk[N];
	void init(void)	{
		memset (rt, -1, sizeof (rt));
		memset (rk, 0, sizeof (rk));
	}
	int Find(int x)	{
		return rt[x] == -1 ? x : rt[x] = Find (rt[x]);
	}
	void Union(int x, int y)	{
		x = Find (x);	y = Find (y);
		if (x == y)	return ;
		if (rk[x] > rk[y])	{
			rt[y] = x;	rk[x] += rk[y] + 1;
		}
		else	{
			rt[x] = y;	rk[y] += rk[x] + 1;
		}
	}
	bool same(int x, int y)	{
		return Find (x) == Find (y);
	}
}dsu;

int main(void)	{
	dsu.init ();
	int ans = 0, x, y;
	while (scanf ("%d", &x) == 1)	{
		if (x == -1)	{
			printf ("%d\n", ans);
			dsu.init ();	ans = 0;
			continue;
		}
		scanf ("%d", &y);
		if (dsu.same (x, y))	ans++;
		else	dsu.Union (x, y);
	}

	return 0;
}

 

  

 

并查集(图论) LA 3644 X-Plosives

原文:http://www.cnblogs.com/Running-Time/p/5027108.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!