POJ 1182 食物链
来源:互联网 发布:手机淘宝封面模版 编辑:程序博客网 时间:2024/05/21 07:52
题意就不讲解了,很经典的一道题目,这是链接:<span style="font-family: Arial, Helvetica, sans-serif;">http://poj.org/problem?id=1182</span>
题解:利用并查集,注意考虑合并时的关系更新
</pre><pre name="code" class="cpp">#include<cstdio>#include<cstring>#include<cmath>#include<ctime>#include<algorithm>#include <iostream>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#define INF 0x3f3f3f3f#define maxn 50010using namespace std;int parent[50010], relation[50010]; //parent[x]是x的父节点 relation[x]是x与根节点的关系int N, K, X, Y, D, ans = 0;void init(){ for(int i = 0; i < N; i++) { parent[i] = i; relation[i] = 0; }} //初始化数组int find(int x){ if(x != parent[x]) { int temp = parent[x]; parent[x] = find(temp); //必须先从父节点更新 relation[x] = (relation[x] + relation[temp]) % 3; //不断更新当前节点与根节点关系 } return parent[x];} //寻找x的根节点void Union(){ int px = find(X); int py = find(Y); parent[py] = px; relation[py] = (D - 1 + 3 - relation[Y] + relation[X]); //更新Y根节点与总的根节点关系} //合并X,Yint main(){ scanf("%d%d", &N, &K); init(); while(K--) { scanf("%d%d%d", &D, &X, &Y); if(X > N || Y > N) ans++; else if(D == 2 && X == Y) ans++; else { if(find(X) == find(Y)) { if((3 - relation[X] + relation[Y]) % 3 != D - 1) //3-部分是X与根节点关系 relation[Y]是根节点与X关系 加起来就是X与Y关系 ans++; } else Union(); } } printf("%d\n",ans); return 0;}
0 0
- poj 1182 食物链
- poj 1182 食物链
- poj 1182 食物链(转)
- poj 1182 食物链
- poj 1182 食物链
- poj 1182 食物链
- POJ-1182 食物链
- POJ 1182 食物链
- poj 1182食物链
- POJ 1182 食物链
- POJ 1182 食物链
- poj 1182 食物链
- POJ 1182 食物链
- POJ 1182 食物链
- poj 1182 食物链
- POJ 1182 - 食物链
- poj 1182 食物链
- poj 1182 食物链
- mysql中文乱码解决方案
- 几何画板中的轨迹法怎样构造双曲线
- win10 亮度不能调节的解决办法(亲测办法,安装两台win10两台都是这样解决)
- UI星辰:UI代码创建视图和Label设置
- 关于STRUCT命名的问题
- POJ 1182 食物链
- POJ 3468-A Simple Problem with Integers(线段树)
- F.lux——自动调整屏幕亮度与颜色,降低蓝光
- 黑马程序员——JAVA面向对象的特性:封装,继承,多态
- 九度oj 1067
- android中的与GPS定位的API
- 测试管理之我见
- HDOJ 2544 最短路 (最短路 Dijkstra && SPFA && Floyd)
- Spark MLlib系列(二):基于协同过滤的电影推荐系统