zoukankan      html  css  js  c++  java
  • E

    题目链接:https://vjudge.net/contest/271361#problem/E

    具体思路:运用并查集,每一次连接上一个点,更新他的父亲节点,如果父亲节点相同,则构不成树,因为入读是2,然后再去遍历每一个点的父亲节点,判断一下祖宗节点有几个,只有1个才能构成树,注意0 0也是树.。。

    AC代码:

     1 #include<iostream>
     2 #include<stack>
     3 #include<queue>
     4 #include<iomanip>
     5 #include<stdio.h>
     6 #include<algorithm>
     7 #include<string>
     8 #include<cstring>
     9 #include<cmath>
    10 #include<map>
    11 using namespace std;
    12 # define inf 0x3f3f3f3f
    13 # define maxn 10000
    14 int father[maxn];
    15 int vis[maxn];
    16 int k;
    17 map<int,int>q;
    18 int Find(int t)
    19 {
    20     return t==father[t]?t:father[t]=Find(father[t]);
    21 }
    22 void match(int t1,int t2)
    23 {
    24     int x=Find(t1);
    25     int y=Find(t2);
    26     if(x!=y)
    27     {
    28         father[y]=x;
    29         return ;
    30     }
    31     else
    32         k=1;
    33 }
    34 int main()
    35 {
    36     int x,y;
    37     int num=0;
    38     while(~scanf("%d %d",&x,&y))
    39     {
    40         q.clear();
    41         k=0;
    42         if(x==-1&&y==-1)break;
    43         memset(vis,0,sizeof(vis));
    44         if(x==0&&y==0)
    45         {
    46             printf("Case %d is a tree.
    ",++num);
    47             continue;
    48         }
    49         for(int i=1; i<=maxn; i++)
    50         {
    51             father[i]=i;
    52         }
    53         vis[x]=1;
    54         vis[y]=1;
    55         match(x,y);
    56         while(~scanf("%d%d",&x,&y))
    57         {
    58             if(x==0&&y==0)break;
    59             match(x,y);
    60             vis[x]=1;
    61             vis[y]=1;
    62         }
    63         if(k==1)printf("Case %d is not a tree.
    ",++num);
    64         else
    65         {
    66             int flag=0;
    67             for(int i=1; i<=maxn; i++)
    68             {
    69                 if(vis[i])
    70                 {
    71                     int temp=Find(i);
    72                     q[temp]=1;
    73                 }
    74             }
    75             if(q.size()==1) printf("Case %d is a tree.
    ",++num);
    76                 else printf("Case %d is not a tree.
    ",++num);
    77         }
    78     }
    79     return 0;
    80 }
    81  

     

  • 相关阅读:
    POJ 1201 Intervals(差分约束 区间约束模版)
    POJ 3660 Cow Contest(求图的传递性)
    POJ 2267 From Dusk till Dawn or: Vladimir the Vampire(最短路变形)
    三角形面积
    欧几里得算法及扩展算法。
    康托展开和排列枚举方式
    并查集 HDU-4424
    poj 2513 并查集,Trie(字典树), 欧拉路径
    hdu 4486
    Pythagorean Triples CodeForces
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10262812.html
Copyright © 2011-2022 走看看