zoukankan      html  css  js  c++  java
  • poj1308(简单并查集)

    题目链接:http://poj.org/problem?id=1308

    题意:x, y 表示x 与 y连接,给出一波这样的数据,问这组数据能否构成树,即不能形成回路,不能有多个根节点;要注意可以是空树;

    代码:

     1 #include <iostream>
     2 #include <stdio.h>
     3 #define MAXN 1000000
     4 using namespace std;
     5 
     6 int pre[MAXN], flag;
     7 
     8 int find(int x){
     9     int r=x;
    10     while(pre[r]!=r){
    11         r=pre[r];
    12     }
    13     int i=x;
    14     while(i!=r){
    15         int gg=pre[i];
    16         pre[i]=r;
    17         i=gg;
    18     }
    19     return r;
    20 }
    21 
    22 int jion(int x, int y){
    23     int xx=find(x);
    24     int yy=find(y);
    25     if(xx!=yy){
    26         pre[xx]=yy;
    27     }else{
    28         flag=0;
    29     }
    30 }
    31 
    32 int main(void){
    33     int a, b, t=1;
    34     while(scanf("%d%d", &a, &b)&&(a!=-1&&b!=-1)){
    35         if(!a&&!b){
    36             printf("Case %d is a tree.
    ", t++);
    37         }else{
    38             flag=1;
    39             int Max=0, c[MAXN], d[MAXN], i=1;
    40             Max=max(Max, max(a, b));
    41             c[0]=a, d[0]=b;
    42             int x, y;
    43             while(scanf("%d%d", &x, &y)&&x&&y){
    44                 c[i]=x;
    45                 d[i]=y;
    46                 Max=max(Max, max(x, y));
    47                 i++;
    48             }
    49             for(int j=1; j<=Max; j++){
    50                 pre[j]=j;
    51             }
    52             for(int j=0; j<i; j++){
    53                 jion(c[j], d[j]);
    54             }
    55             int ans=0;
    56             for(int j=0; j<i; j++){
    57                 if(c[j]==pre[c[j]]){
    58                     ans++;
    59                 }else if(d[j]==pre[d[j]]){
    60                     ans++;
    61                 }
    62             }
    63             if(ans>1 || flag==0){
    64                 printf("Case %d is not a tree.
    ", t++);
    65             }else{
    66                 printf("Case %d is a tree.
    ", t++);
    67             }
    68         }
    69     }
    70     return 0;
    71 }
  • 相关阅读:
    面向对象之补充
    继续面向对象之成员与组合
    面向对象初阶
    模块和包
    异常处理
    [Array]448. Find All Numbers Disappeared in an Array
    [Array]485. Max Consecutive Ones
    [Array] 561. Array Partition I
    [Array] 566. Reshape the Matrix
    opencv3.1线性可分svm例子及函数分析
  • 原文地址:https://www.cnblogs.com/geloutingyu/p/5998318.html
Copyright © 2011-2022 走看看