之前在CSDN看到一篇很受欢迎的讲解并查集的博文,其中自然用到了路径压缩: int pre[1000]; int find(int x){ int root = x; while(pre[root]!=root) root = pre[root]; int i = x,j; while(i!=root){ //path compress j = pre[i]; pre[i] = root; i = j; } return root; } void join(int x,int y){ int f…
/* 题目大意:有两个不同的黑帮,开始的时候不清楚每个人是属于哪个的! 执行两个操作 A a, b回答a, b两个人是否在同一帮派,或者不确定 D a, b表示a, b两个人不在同一个帮派 思路:利用并查集将相同帮派的人合并到一起! a ,b 不在同一个城市,那么 a, 和mark[b]就在同一个城市, b 和 mark[a]就在同一个城市! */ #include<iostream> #include<cstring> #include<cstdio> #define…
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2818 题意:有N个块,每次有两个操作: M x y表示把x所在的那一堆全部移到y所在的那一堆的下方. C x 询问在x下方有多少个方块. 用并查集,在路径压缩的时候后序更新当前块下有多少个其他块,注意这里“当前块下”其实和并查集是相反的,也就是父亲节点在儿子下面. 需要额外维护一个量:某一堆的块的总数,这个在unite操作的时候,如果不是同一个根,直接将一部分加到另一部分上就可以. /* ━━━━━…
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3635 题意:有n个龙珠,n个城市.初始状态第i个龙珠在第i个城市里.接下来有两个操作: T A B:把A号龙珠所在的城市的所有龙珠全部转移到B城市中. Q A:查询A龙珠,要求:A龙珠所在城市,该城市龙珠数量,A移动的次数. 思路:用并查集可以轻松解决Q的前两个问题.关键在于如何统计A的移动次数,因为在T的时候是要将A所在城市的所有龙珠都要转移到B,那就要A集合里所有龙珠的移动次数都+1.假如我们在…
/* bzoj 3674: 可持久化并查集加强版 http://www.lydsy.com/JudgeOnline/problem.php?id=3674 用可持久化线段树维护可持久化数组从而实现可持久化并查集 可持久化线段树+并查集+路径压缩+读入优化 */ #include <cstdio> #include <algorithm> using namespace std; ; int root_fa[Nmax]; inline int read() { ;char ch=ge…
public class unionfind2 implements UF { int[] parent; int[] rank; public unionfind2(int n) { parent=new int[n]; rank=new int[n]; for(int i=0;i<parent.length;i++) { parent[i]=i; rank[i]=1; } } private int find(int i) { while(i!=parent[i]) { parent[i]=…
F. Asya And Kittens Asya loves animals very much. Recently, she purchased nn kittens, enumerated them from 11 and nn and then put them into the cage. The cage consists of one row of nn cells, enumerated with integers from 11 to nn from left to right.…
确定比赛名次 Problem Description 有N个比赛队(1<=N<=500),编号依次为1,2,3,....,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前.现在请你编程序确定排名. Input 输入有若干组,每组中的第一行为二个数N(1<=N<=500),M:其中N表示队伍的个数,M表示接着有M行的输入数据.接下来的M行数据中,…
题目大意:有n个节点,初始时每个节点的父亲节点都不存在.有两种操作 I u v:把点节点u的父亲节点设为v,距离为|u-v|除以1000的余数.输入保证执行指令前u没有父亲节点. E u:询问u到根节点的距离. 分析:并查集加路径压缩. #include<iostream> #include<algorithm> #include<cstring> #include<cstdio> using namespace std; ; int f[maxn],d[m…
在很多时候,并查集并不是一个完整的解题方法,而是一种思路. 通过以下题目来体会并查集逆向运用的思想. Description Farmer John and his cows are planning to leave town for a long vacation, and so FJ wants to temporarily close down his farm to save money in the meantime.The farm consists of NN barns con…