zoukankan      html  css  js  c++  java
  • HDOJ 2473 并查集

    就知道会超时,时限 8ms,1 ≤ N ≤ 105 , 1 ≤ M ≤ 106,循环查找当然超时;

    有点新意的并查集。

     1 # include <stdio.h>
    2
    3 # define MAXN 100005
    4
    5 int father[MAXN];
    6
    7 int main()
    8 {
    9 int N, M, i, cnt, ch, x, y, f, tmp, p, clo = 0;;
    10
    11 while (1)
    12 {
    13 scanf("%d%d", &N, &M);
    14 getchar();
    15 if (!N && !M) break;
    16 cnt = 0;
    17 for (i = 1; i <= N; ++i)
    18 father[i] = i;
    19 while (M--)
    20 {
    21 ch = getchar();
    22 if (ch == 'M')
    23 {
    24 scanf("%d%d", &x, &y);
    25 getchar();
    26 while (x != father[x]) x = father[x];
    27 while (y != father[y]) y = father[y];
    28 if (x != y)
    29 {
    30 ++cnt;
    31 father[y] = x;
    32 }
    33 }
    34 else if (ch == 'S')
    35 {
    36 scanf("%d", &x);
    37 getchar();
    38 if (x != father[x])
    39 {
    40 tmp = father[x];
    41 for (i = 1; i <= N; ++i)
    42 if (father[i] = x) father[i] = tmp;
    43 father[x] = x;
    44 --cnt;
    45 }
    46 else
    47 {
    48 f = 1;
    49 for (i = 1; i <= N; ++i)
    50 if (father[i] = x)
    51 {
    52 if (f) {father[i] = i; p = i; f = 0;}
    53 else father[i] = p;
    54 }
    55 father[x] = x;
    56 if (!f) --cnt;
    57 }
    58 }
    59 }
    60 getchar();
    61 printf("Case #%d: %d\n", ++clo, N-cnt);
    62 }
    63
    64 return 0;
    65 }
  • 相关阅读:
    顺序队列的模板
    链式队列模板
    链式栈模板
    栈应用hanoi
    判断出栈顺序
    用栈实现四则运算
    两栈共享问题
    The Preliminary Contest for ICPC Asia Nanjing 2019
    Educational Codeforces Round 71 (Rated for Div. 2)
    HDU6583:Typewriter(dp+后缀自动机)
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2404814.html
Copyright © 2011-2022 走看看