博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
poj 1703 Find them, Catch them(带权并查集)
阅读量:3712 次
发布时间:2019-05-21

本文共 1479 字,大约阅读时间需要 4 分钟。

题目链接:

题目大意:

给出一些人,给出一些信息,告知那两个罪犯不再同一个监狱当中,再给出一些查询,询问两个罪犯的关系

题目分析:

带权并查集裸题,定义一个基本的并查集数组fa[MAX],再定义一个rank数组,用来表示当前节点到根的关系,这个关系具有传递性和交换性,也满足结合律,所以可以利用到根的关系,推导出两点的关系。对于两点先判断是否在同一个关系集合中,如果在同一个关系集合中的话,那么判断他们的关系,如果不在同一个关系集合中,那么他们的关系不能确定

代码如下:

#include 
#include
#include
#include
#define MAX 100007using namespace std;int n,m,t;int rank[MAX];int fa[MAX];void init ( int n){ for ( int i = 1 ; i <= n ; i++ ) fa[i] = i; memset ( rank , 0 , sizeof ( rank ));}int find ( int x ){ if ( fa[x] == x ) return x; int temp = find ( fa[x] ); rank[x] = rank[x]^rank[fa[x]]; return fa[x] = temp;}void _union ( int x , int y ){ int fx = find ( x ); int fy = find ( y ); fa[fx] = fy; rank[fx] = rank[x]^rank[y]^1;}char s[5];bool judge ( int u , int v ){ return rank[u]^rank[v] == 0;}int main (){ int x ,y; scanf ( "%d" , &t ); while ( t-- ) { scanf ( "%d%d" , &n , &m ); init( n ); while ( m-- ) { scanf ( "%s" , s ); scanf ( "%d%d" , &x , &y ); if ( s[0] == 'A' ) { if ( find(x) == find (y)) { if ( judge ( x , y ) ) puts ( "In the same gang."); else puts ( "In different gangs."); } else puts ( "Not sure yet."); } else { _union ( x , y ); } } }}

转载地址:http://jvvjn.baihongyu.com/

你可能感兴趣的文章
Kali 2020.2虚拟机安装及安装后配置教程(图文小白版)
查看>>
C语言编程0基础学习历程(7)——C的函数
查看>>
洛谷——P2241 统计方形(数据加强版)(数学+暴力枚举)
查看>>
Windows Server 2008 安装教程——图文小白版(附下载地址)
查看>>
Windows Server 2003 安装教程——图文小白版(附下载地址)
查看>>
Jarvis OJ BASIC 公倍数
查看>>
sqli-lab 闯关教程 Less-1
查看>>
sqli-lab 闯关教程 Less-2
查看>>
sqli-lab 闯关教程 Less-3
查看>>
sqli-lab 闯关教程 Less-4
查看>>
sqli-lab 闯关教程 Less-5
查看>>
Ping 命令详解(含真实操作截图)
查看>>
L1-002 打印沙漏 (20分) C++版 AC代码
查看>>
L1-005 考试座位号 (15分) C++版 AC代码
查看>>
L1-049 天梯赛座位分配 (20分) AC代码
查看>>
L1-006 连续因子 (20分) C++版 AC代码
查看>>
C# 计算器窗体程序
查看>>
虚拟机安装winxp系统出现 non-bootable disk 80 的解决办法
查看>>
鼠标指针乱跑的解决方案
查看>>
Windows消息函数
查看>>