zoukankan      html  css  js  c++  java
  • POJ 1984 Navigation Nightmare

    转载来自: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;
     }


  • 相关阅读:
    css样式详解
    数组去重的两种方式
    react 中class样式的书写过程及注意点
    react 行内样式几种写法
    React创建组件的两种方法
    React中class创建组件和function创建组件的区别
    class关键字
    关于webpack配置环境,以及自己搭建react环境
    经典圣杯双飞翼布局
    关于vue中深拷贝的惨痛教训
  • 原文地址:https://www.cnblogs.com/freezhan/p/3219081.html
Copyright © 2011-2022 走看看