Hud 1325 Is It A Tree?

Step5.1.2Hud 1325

 Is It A Tree?

ProblemDescription

A tree is awell-known data structure that is either empty (null, void, nothing) or is aset of one or more nodes connected by directed edges between nodes satisfyingthe following properties.

There is exactlyone node, called the root, to which no directed edges point.

Every node exceptthe root has exactly one edge pointing to it.

There is a uniquesequence of directed edges from the root to each node.

For example,consider the illustrations below, in which nodes are represented by circles andedges are represented by lines with arrowheads. The first two of these aretrees, but the last is not.

 

In this problemyou will be given several descriptions of collections of nodes connected bydirected edges. For each of these you are to determine if the collectionsatisfies the definition of a tree or not.

第一道并查集的题。

题解

就是判断所给的关系是否满足一棵树的要求,即每一个结点只有一个父结点,并且两个结点不能够相互为父结点,两个结点在表明有关系前不能再同一棵树里(即祖孙,父子,或一棵树里的远亲关系)。自己不能是自己的父结点,空树也是一棵树。

源代码:

#include <iostream>

#include <string>

#define MAX 100000

using namespace std;

 

struct node

{

   intrank;

   intparent;

} tree[MAX];

 

void init()

{

   for(int i = 0;i < MAX;i++)

   {

     tree[i].parent = i;

     tree[i].rank = 0;

   }

}

 

int get_parent(int a)

{

   if(a== tree[a].parent)

     returna;

   else

     returnget_parent(tree[a].parent);

}

 

int main()

{

   inta,b;

   boolflag = true;

   intcount = 1;

 

   init();

   while(cin>> a >> b)

   {

     if(a< 0 && b < 0)

        break;

 

     if(!flag&& a && b)

        continue;

 

     if(!a&& !b)

     {

        if(flag)

        {

          intnum = 0;

          for(int i = 1;i < MAX;i++)

          {

             if(tree[i].rank&& tree[i].parent == i)

               num++;

          }

          if(num> 1)

             flag = false;

        }

 

       

 

        if(flag)

          cout << "Case "<< count++ <<" is a tree." << endl;

        else

          cout << "Case "<< count++ <<" is not a tree." << endl;

 

        init();

        flag = true;

 

        continue;

     }

     else

     { 

        if((a!= b && get_parent(a) == get_parent(b)) || a == b || tree[b].parent !=b)

          flag = false;

        else

        {

          tree[b].parent = a;

          tree[b].rank = 1;

          tree[a].rank = 1;

        }

     }

   }

   return0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值