POJ 1984 Navigation Nightmare
来源:互联网 发布:三星4821hn网络打印 编辑:程序博客网 时间:2024/05/16 05:47
转载来自:http://www.cnblogs.com/huangfeihome/archive/2012/09/07/2675123.html
并查集。
首先,以为k个询问中的I是乱序的,直接被吓傻了,后来看讨论版才发现I是升序的……
这道题让我对并查集有一个新的认识:根的代表性是非常强的!并查集里如果某个节点的改动会影响到整个并查集的所有节点,那么,在union_set的时候只需要改动根节点就可以了,当然,在find_set函数里要对所有节点进行更新(这相当于一种延时标记)。我们知道,find_set函数走了两条路,一条是前往根的路,一条是从跟返回的路,那么,如果发现根已经被改动,必须在从根返回的路上更新经过的所有节点。这在find_set函数里是可以实现的。
#include <stdio.h> #include <math.h> #include <stdlib.h> #define N 40005 int f[N], cx[N], cy[N]; int f1[N], f2[N], len[N]; char dr[N]; int find(int x) { int tmp; if(x != f[x]) { tmp = f[x]; f[x] = find(f[x]); cx[x] = cx[x] + cx[tmp]; // 从根回来的路上更新子节点 cy[x] = cy[x] + cy[tmp]; } return f[x]; } void make_set(int n) { for(int i = 0; i <= n; i ++) { f[i] = i; cx[i] = cy[i] = 0; } } void union_set(int j) { int x = find(f1[j]); int y = find(f2[j]); f[y] = x; // 随意合并 cx[y] = cx[x] + cx[f1[j]] - cx[f2[j]]; // 暂且只对根进行偏移 cy[y] = cy[x] + cy[f1[j]] - cy[f2[j]]; switch(dr[j]) { case 'W': cx[y] -= len[j]; break; case 'E': cx[y] += len[j]; break; case 'S': cy[y] -= len[j]; break; case 'N': cy[y] += len[j]; break; } } int main() { int n, m, i, j, k, q, a, b, c, x, y; while(scanf("%d%d", &n, &m) != EOF) { make_set(n); for(i = 0; i < m; i ++) scanf("%d%d%d %c", &f1[i], &f2[i], &len[i], &dr[i]); scanf("%d", &q); for(k = i = 0; i < q; i ++) { scanf("%d%d%d", &a, &b, &c); for(j = k; j < c; j ++) union_set(j); k = c; x = find(a); y = find(b); if(x != y) printf("-1\n"); else printf("%d\n", abs(cx[a] - cx[b]) + abs(cy[a] - cy[b])); } } return 0; }
- POJ 1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare
- POJ-1984-Navigation Nightmare
- POJ 1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare
- POJ-1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare
- Navigation Nightmare poj 1984
- poj 1984 Navigation Nightmare
- POJ 1984 Navigation Nightmare 笔记
- 【POJ 1984】Navigation Nightmare (并查集)
- POJ--1984-Navigation Nightmare--并查集
- poj 1984 - Navigation Nightmare(并查集)
- POJ 1984 Navigation Nightmare 并查集
- Navigation Nightmare POJ
- [POJ P1984]Navigation Nightmare
- C++11 --右值引用(Rvalue Reference) Part1
- typedef和#define的用法及区别
- iOS有几种不同的键盘布局
- opencv2.4.2在VS2010下的配置
- 第五次作业
- POJ 1984 Navigation Nightmare
- HDU 1565(方格取数)
- The Clocks
- jbpm安装
- Python 代码性能优化技巧
- Jquery实战学习--必须选中条约才能继续操作
- 泛型操作范例
- 谈谈怎么实现Oracle数据库分区表
- 50个令人叹为观止的JavaScript应用站点