POJ 1703Find them, Catch them(经典并查集)
来源:互联网 发布:unity 删除整个数组 编辑:程序博客网 时间:2024/06/05 00:15
并查集的经典问题,我用到的是并查集的经典方法。。就是用relation数组记录与根节点的关系,例如relation[i]=1表示i跟i的根节点在同一个集合,relation[i]=0表示i跟i的根节点不在同一个集合。
然后就可以方便的查询他们之间的关系了。
主要是在find和union函数里面要对relation数组的修改,这个修改要自己在不同的题目中细心找出,,,因为找错一次wa了一次,find函数里的修改是递归的对所有访问到的点的relation值全都修改。
#pragma warning(disable:4996)#include <cstdio>#include <iostream>using namespace std;const int N = 100005;int fa[N], relation[N];//relation[i]=1表示i与其根节点属于一个集合,0表示不属于一个集合int find_set(int x) { if (x == fa[x])return fa[x]; //这里递归的先修改了fa[x]的relation值 int ret = find_set(fa[x]); //如果根节点跟x的父节点不同的话我们就要更新x的relation值 if (ret != fa[x]) { relation[x] = (relation[fa[x]] + relation[x]) == 1 ? 0 : 1; fa[x] = ret; } return ret;}void union_set(int x, int y) { int fx = find_set(x); int fy = find_set(y); if (fx != fy) { fa[fx] = fy; relation[fx] = (relation[x] + relation[y]) == 1 ? 1 : 0; }}int main() { //freopen("in.txt", "r", stdin); int t; scanf("%d", &t); while (t--) { int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { fa[i] = i; relation[i] = 1; } for (int i = 0; i < m; i++) { char ch; int x, y; getchar(); scanf("%c %d %d", &ch, &x, &y); if (ch == 'D') { union_set(x, y); } else { int fx = find_set(x), fy = find_set(y); if (fx == fy) { if (relation[x] == relation[y])printf("In the same gang.\n"); else printf("In different gangs.\n"); } else { printf("Not sure yet.\n"); } } } } return 0;}
0 0
- POJ-1703 Find them, Catch them 经典并查集
- poj 1703 Find them, Catch them(并查集)
- poj 1703 Find them, Catch them (并查集)
- poj 1703 -- Find them, Catch them(并查集)
- poj 1703 Find them, Catch them(并查集)
- poj 1703 Find them, Catch them (并查集)
- POJ 1703 Find them, Catch them (并查集)
- Find them, Catch them.(POJ-1703)(并查集)
- POJ - 1703 - Find them, Catch them (并查集)
- POJ 1703 Find them, Catch them(并查集)
- poj--1703 Find them, Catch them(并查集)
- POJ 1703 Find them, Catch them (并查集)
- poj 1703 Find them, Catch them(并查集)
- POJ 1703-Find them, Catch them(并查集)
- poj 1703 Find them, Catch them(并查集)
- Poj 1703 Find them, Catch them (并查集)
- POJ 1703Find them, Catch them(经典并查集)
- POJ 1703 Find them, Catch them(并查集)
- java__集合的工具类
- rectint 函数
- linux grep命令
- 开启新的篇章
- 标准SQL的update语句三种用法
- POJ 1703Find them, Catch them(经典并查集)
- 将mongodb启动做成服务
- java中Map,List与Set的区别
- TCP/IP三次握手与四次握手
- C++的STL进一步总结之pair
- [dijkstra]
- 使用PHP的GET和POST实现iOS的http网络通信
- ArcEngine实现空间分析
- 探讨read的返回值的三种情况