并查集初学(2)LA 3644 & LA3027
来源:互联网 发布:startos安装软件 编辑:程序博客网 时间:2024/05/18 23:28
1、LA 3644
题目:http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=12648
并查集入门题,寻找是否存在环,若存在,则cnt++
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>const int maxn=100010;using namespace std;int p[maxn];//带路径压缩的并查集int Find(int x){return p[x] == x?x:p[x]=Find(p[x]);}int main(){ int x,y; while (scanf("%d",&x) == 1) { for (int i=0;i<maxn;i++) p[i]=i; int cnt=0; while (x != -1) { scanf("%d",&y); x=Find(x); y=Find(y); if (x == y) cnt++; else p[x]=y; scanf("%d",&x); } printf("%d\n",cnt); } return 0;}
2、LA 3027
题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33982
分析:一边路径压缩,一边维护d[i] : 结点i到树根的距离
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn=20010;int p[maxn];int d[maxn];int Find(int x){ if (p[x] != x) { int root=Find(p[x]); d[x] += d[p[x]]; return p[x]=root; } else return x;}int main(){ int T; scanf("%d",&T); while (T--) { int n,u,v; char cmd[9]; scanf("%d",&n); for (int i=1;i<=n;i++) { p[i]=i; d[i]=0; } while (scanf("%s",cmd) && cmd[0] != 'O') { if (cmd[0] == 'I') { scanf("%d%d",&u,&v); p[u]=v; d[u]=abs(u-v) % 1000; } if (cmd[0] == 'E') { scanf("%d",&u); int t=Find(u); printf("%d\n",d[u]); } } } return 0;}
0 0
- 并查集初学(2)LA 3644 & LA3027
- 并查集LA3027
- LA3027(并查集)
- LA3027之并查集
- 并查集uva1329(LA3027)
- LA3027 - Corporative Network,并查集
- LA3027 带权并查集
- LA3027简单带权并查集
- LA3027:Corporative Network(并查集)
- LA 3644(并查集)
- LA 3644 并查集
- 并查集 LA 3644
- LA 3644 并查集
- 并查集 LA 3644
- LA 3644 (并查集)
- LA 3644并查集
- LA 3644并查集
- 初学并查集的例题1 X-Plosives,LA 3644
- Spark中的二次排序
- Linux C++学习之路
- 你是否恰当地使用了枚举------强烈建议对枚举进行显式赋值
- C++ explicit关键字
- linux下C++开发工具
- 并查集初学(2)LA 3644 & LA3027
- Android之十一实现登陆页面分析
- Linux下常用的C/C++开源Socket库
- map同步数据库/后台缓存
- Android5.1系统WebView内存泄漏场景
- Hash Compared & ELFHash 详解
- 桌面图标没有是解决方法windown
- 3D 游戏控制
- Spark中的各种action算子操作(java版)