• [luoguP1196] 银河英雄传说(并查集)


    传送门

    记录 up[x] 表示 x 上方有多少个

       all[x] 表示当前连通的有多少个

    find 的时候 和 合并的时候 更新一下即可

    ——代码

     1 #include <cstdio>
     2 #include <iostream>
     3 #define N 30001
     4 #define abs(x) ((x) < 0 ? -(x) : (x))
     5 
     6 int T;
     7 int f[N], up[N], all[N];
     8 
     9 inline int read()
    10 {
    11     int x = 0, f = 1;
    12     char ch = getchar();
    13     for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
    14     for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
    15     return x * f;
    16 }
    17 
    18 inline int find(int x)
    19 {
    20     if(x ^ f[x])
    21     {
    22         int fx = f[x];
    23         f[x] = find(f[x]);
    24         up[x] += up[fx];
    25     }
    26     return f[x];
    27 }
    28 
    29 int main()
    30 {
    31     int i, x, y, fx, fy;
    32     char s[1];
    33     T = read();
    34     for(i = 1; i < N; i++) f[i] = i, all[i] = 1;
    35     while(T--)
    36     {
    37         scanf("%s", s);
    38         x = read();
    39         y = read();
    40         fx = find(x);
    41         fy = find(y);
    42         if(s[0] == 'M')
    43         {
    44             f[fx] = fy;
    45             up[fx] += all[fy];
    46             all[fy] += all[fx];
    47         }
    48         else fx ^ fy ? puts("-1") : printf("%d
    ", abs(up[x] - up[y]) - 1);
    49     }
    50     return 0;
    51 }
    View Code
  • 相关阅读:
    入侵特斯拉——智能汽车安全性分析
    D-Link系列路由器漏洞挖掘入门
    工控安全入门之 Ethernet/IP
    浅谈JS数据类型存储问题
    【备忘】12306购票必杀技
    制作炫酷的专题页面
    杂记(下)
    杂记(上)
    跨域请求解决方案
    好用的表单验证插件
  • 原文地址:https://www.cnblogs.com/zhenghaotian/p/7043458.html
Copyright © 2020-2023  润新知