zoukankan      html  css  js  c++  java
  • N

    题目大意:

           跟小希的迷宫差不多,其实这个题的代码我用小希的代码加了一个判断条件就AC了。

    解题思路:

           看到别人的易错情况:

    1、0 0 yes

    2、1 1 0 0 no

    3、1 2 1 2 0 0 no 

    4、1 2 2 3 4 5 0 0 no (多个根结点)

    5、1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 0 0  no(环?一个结点指向祖先)

    6、1 2 2 1 0 0 no

    参考代码:

     1 #include <iostream>
     2 #include <vector>
     3 #include <map>
     4 #include <string>
     5 #include <queue>
     6 #include <stack>
     7 #include <set>
     8 
     9 #include <cstdio>
    10 #include <cstring>
    11 #include <cmath>
    12 #include <cstdlib>
    13 using namespace std;
    14 
    15 const int INF=0x3f3f3f3f;
    16 const int SIZE=1e5+10;
    17 
    18 set<int> st;  ///这个是为了两两查找的时候方便一点
    19 int id[SIZE];
    20 int sz[SIZE];
    21 int count;
    22 int find(int x)  ///找跟根结点
    23 {
    24     while(x!=id[x])
    25     {
    26         id[x]=id[id[x]];
    27         x=id[x];
    28     }
    29     return x;
    30 }
    31 
    32 int un(int p,int q)
    33 {
    34     int pr=find(p);
    35     int qr=find(q);
    36     if(pr==qr) return -1;
    37     if(sz[pr]<=sz[qr])
    38     {
    39         sz[qr]+=sz[pr];id[pr]=qr;
    40     }
    41     else
    42     {
    43         sz[pr]+=sz[qr];id[qr]=pr;
    44     }
    45 }
    46 
    47 void clear()
    48 {
    49     for(int i=1;i<=SIZE;i++)
    50     {
    51         id[i]=i;sz[i]=1;
    52     }
    53     st.clear();
    54 }
    55 
    56 int main()
    57 {
    58     int p,q;
    59     int temp,flag;
    60     int cas=1;
    61     while(cin>>p>>q)
    62     {
    63         flag=0;
    64         clear();
    65         if(p==-1&&q==-1) break;
    66         if(p==0&&q==0) {cout<<"Case "<<cas<<" is a tree.
    ";cas++;continue;}///特判0 0的情况
    67         if(p==q) flag=1;  ////*************小希的迷宫增加的唯一判断
    68         st.insert(p);
    69         st.insert(q);
    70         un(p,q);
    71         int mark=p;
    72 
    73         while(cin>>p>>q)
    74         {
    75             if(p==0&&q==0) break;
    76             if(p==q) flag=1; //////////*******小希的迷宫增加的唯一判断
    77             if(!flag)
    78                 temp=un(p,q);
    79             if(temp==-1) flag=1;
    80             st.insert(p);st.insert(q);
    81         }
    82 
    83         count=st.size();
    84         if(sz[find(mark)]<count) flag=1;
    85         if(flag==1) cout<<"Case "<<cas<<" is not a tree.
    ";
    86         else  cout<<"Case "<<cas<<" is a tree.
    ";
    87         cas++;
    88     }
    89     return 0;
    90 }
    91  

      

    まだまだだね
  • 相关阅读:
    Java面试题(3)Java new一个对象的过程中发生了什么
    spring boot(九):Spring Boot中Redis的使用
    intellij idea 2018
    springboot(八)自定义Filter、自定义Property
    springboot(六)SpringBoot问题汇总
    Java Web之路(五)JSP
    Java
    instrument(2)
    Instrumentation(1)
    Dubbo中订阅和通知解析
  • 原文地址:https://www.cnblogs.com/xxQ-1999/p/7469764.html
Copyright © 2011-2022 走看看