并查集初学(4)向量思维 POJ1182(食物链)&& POJ1703
2016-05-08 09:37
441 查看
分析:这两个题,便算是初学者中的大成题了,学会了这两个题,几乎并查集算是入门了,可以秒掉不少题了
POJ1182
一般博客都只是给了一个公式,不给推导过程,对于这个公式,有很多理解办法,但我认为应该是用向量思维来理解最好,简单明了
此大神写的详解非常完美(可以借鉴):http://blog.csdn.net/c0de4fun/article/details/7318642/
这位大牛也非常牛:http://blog.csdn.net/freezhanacmore/article/details/8767413
我只能写出代码,还不能很完美的解释此问题,仰视大牛:::::
2、第二个类似第一个,将食物链的三类改成了两类,一边路径压缩,一边关系域更新便可
POJ1182
一般博客都只是给了一个公式,不给推导过程,对于这个公式,有很多理解办法,但我认为应该是用向量思维来理解最好,简单明了
此大神写的详解非常完美(可以借鉴):http://blog.csdn.net/c0de4fun/article/details/7318642/
这位大牛也非常牛:http://blog.csdn.net/freezhanacmore/article/details/8767413
我只能写出代码,还不能很完美的解释此问题,仰视大牛:::::
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define N 50010 struct node { int pre; int relation; }; node p ; int find(int x) //查找根结点 { int temp; if(x == p[x].pre) return x; temp = p[x].pre; //路径压缩 p[x].pre = find(temp); p[x].relation = (p[x].relation + p[temp].relation) % 3; //关系域更新 return p[x].pre; //根结点 } int main() { int n, k; int ope, a, b; int root1, root2; int sum = 0; //假话数量 scanf("%d%d", &n, &k); for(int i = 1; i <= n; ++i) //初始化 { p[i].pre = i; p[i].relation = 0; } for(int i = 1; i <= k; ++i) { scanf("%d%d%d", &ope, &a, &b); if(a > n || b > n) //条件2 { sum++; continue; } if(ope == 2 && a == b) //条件3 { sum++; continue; } root1 = find(a); root2 = find(b); if(root1 != root2) // 合并 { p[root2].pre = root1; p[root2].relation = (3 + (ope - 1) +p[a].relation - p[b].relation) % 3; } else { if(ope == 1 && p[a].relation != p[b].relation) { sum++; continue; } if(ope == 2 && ((3 - p[a].relation + p[b].relation) % 3 != ope - 1)) { sum++; continue;} } } printf("%d\n", sum); return 0; }
2、第二个类似第一个,将食物链的三类改成了两类,一边路径压缩,一边关系域更新便可
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn=100005; int p[maxn],ans[maxn]; int n; void init() { for (int i=1;i<=n;i++) { p[i]=i; ans[i]=0; } } int Find(int x) { if (x == p[x]) return x; //注意tp的使用 int tp=Find(p[x]); ans[x]=ans[x]^ans[p[x]]; return p[x]=tp; } void Union(int x,int y) { int fx=Find(x); int fy=Find(y); p[fx]=fy; ans[fx]=~(ans[y]^ans[x]); } int main() { int t,m; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); init(); char relation[2]; int a,b; for (int i=0;i<m;i++) { scanf("%s%d%d",relation,&a,&b); if (relation[0] == 'D') Union(a,b); else { if (n == 2) { printf("In different gangs.\n"); } else if (Find(a) == Find(b)) { if (ans[a] == ans[b]) printf("In the same gang.\n"); else printf("In different gangs.\n"); } else printf("Not sure yet.\n"); } } } return 0; }
相关文章推荐
- 十进制转二进制
- 第5课:基于案例一节课贯通Spark Streaming流计算框架的运行源码
- 8--项目采购管理、信息管理和配置
- 欢迎使用CSDN-markdown编辑器
- android面试大宝典
- 图片缓存构架
- [转]深入理解Java的接口和抽象类
- bzoj 4010: [HNOI2015]菜肴制作(优先队列+拓扑排序)
- 使用android studio的配置及注意事项
- Linux设备驱动(1)模块的相关概念
- Python数据类型详解(二)列表
- 继承和组合、多态性和虚函数
- iOS-HTTP浅析
- 设置每CPU环境
- 各种信息图应用说明
- IntelliJ IDEA —— SVN
- Hybrid APP 架构设计思路
- 第九章:逻辑卷LVM
- 排序算法(综述)
- java课程总结