zoukankan      html  css  js  c++  java
  • POJ 1703 Find them, Catch them(种类并查集)

    题目链接

    这种类型的题目以前见过,今天第一次写,具体过程,还要慢慢理解。

     1 #include <cstring>
     2 #include <cstdio>
     3 #include <string>
     4 #include <iostream>
     5 #include <algorithm>
     6 #include <vector>
     7 using namespace std;
     8 int o[100001];
     9 int flag[100001];
    10 int find(int x)
    11 {
    12     if (x == o[x]) return x;
    13     int t = find(o[x]);
    14     flag[x] = (flag[o[x]] + flag[x]) % 2;
    15     return o[x] = t;
    16 }
    17 void merge(int x,int y)
    18 {
    19     int tx,ty;
    20     tx = find(x);
    21     ty = find(y);
    22     if(tx != ty)
    23     {
    24         o[tx] = ty;
    25         flag[tx] = (flag[x]+flag[y]+1)%2;
    26     }
    27 }
    28 int judge(int x,int y)
    29 {
    30     int tx,ty;
    31     tx = find(x);
    32     ty = find(y);
    33     if(tx != ty)
    34     return -1;
    35     else
    36     return (flag[x] == flag[y]);
    37 }
    38 int main()
    39 {
    40     int T,sv,ev,i,n,m;
    41     char ch;
    42     scanf("%d",&T);
    43     while(T--)
    44     {
    45         scanf("%d%d%*c",&n,&m);
    46         for(i = 1;i <= n;i ++)
    47         {
    48             flag[i] = 0;
    49             o[i] = i;
    50         }
    51         for(i = 0;i < m;i ++)
    52         {
    53             scanf("%c%*c%d%d%*c",&ch,&sv,&ev);
    54             if(ch == 'A')
    55             {
    56                 int temp = judge(sv,ev);
    57                 if(temp == -1)
    58                 printf("Not sure yet.
    ");
    59                 else if(temp == 0)
    60                 printf("In different gangs.
    ");
    61                 else
    62                 printf("In the same gang.
    ");
    63             }
    64             else
    65             {
    66                 merge(sv,ev);
    67             }
    68         }
    69     }
    70     return 0;
    71 }
  • 相关阅读:
    2016.7.31整机升级计划
    UVa 1588
    UVa1587
    Jzoj4714 公约数
    Jzoj4714 公约数
    Jzoj4713 A
    Jzoj4713 A
    Jzoj4711 Binary
    Jzoj4711 Binary
    Jzoj4710 Value
  • 原文地址:https://www.cnblogs.com/naix-x/p/3140271.html
Copyright © 2011-2022 走看看