天天看點

Is It A Tree?------HDOJ杭電1325(兩種方法,可以用也可以不用并查集!!!!!!詳解)

Problem Description

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties. 

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

Every node except the root has exactly one edge pointing to it. 

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

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

Is It A Tree?------HDOJ杭電1325(兩種方法,可以用也可以不用并查集!!!!!!詳解)
Is It A Tree?------HDOJ杭電1325(兩種方法,可以用也可以不用并查集!!!!!!詳解)
Is It A Tree?------HDOJ杭電1325(兩種方法,可以用也可以不用并查集!!!!!!詳解)

In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not. 

Input

The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers;

the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero. 

Output

For each test case display the line ``Case k is a tree." or the line ``Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1). 

Sample Input

Sample Output

這道題乍一看!!!!!!并查集啊!!!!!!@¥%……@…………%¥……#¥%&……%&&%&#%……*&……¥@……&……%&#&……&¥#&&¥&%¥!!!!!!

此處省略六萬六千六百六十六個字!!!!!!表達欣喜之情,并查集還是很簡單的!!!!!!

對吧!!!!!!

如果對并查集不怎麼熟悉的童鞋,咱們來小小介紹下某萬能思想:找老大!!!!!!這裡有一篇文章,講的特别好,http://blog.csdn.net/shahongzhou/article/details/8957886,這是連結,大家可以看看!!!!!!

我先劇透一下,就是一級下面還有一級,咱們把他們歸結為一個老大,就是b歸a管,c歸b管,咱們就讓c直接歸a管,直接找到根節點,嗯,劇透完畢!!!!!!

現在咱們來講講這道題,我相信會百度這道題的童鞋一般就兩種情況,并查集不會的,還有這題一直WA的,哈哈哈哈哈哈哈哈哈哈!!!!!!23333333333333!!!!!!

笑笑有益身體健康!!!!!!

并查集不會的先去看看上面的連結的知識,然後做一下杭電的暢通工程!!!!!!不過那個暢通工程不一定都是并查集,知識有一題是,哪一題我忘了!!!!!!

這題就是說給一堆資料,一對一對的,ono!!!!!!今天520,講這麼傷心的東西,一對一對!!!!!!不好意思,又偏題了!!!!!!不過我等ACMER屌絲總是要傷感一下的!!!!!!求了解啊!!!!!!繼續講解題目,不停輸入a,b,代表b是a的子節點,然後a,b都為0的時候輸入結束!

這道題考慮的東西好多啊!!!!!!

坑爹有木有啊!!!!!!

WA的童鞋可以了解的!!!!!!

首先,不能成環!!!!!!

然後不能是樹林!!!!!!

最後,不能有入度為2的節點!!!!!!

先貼下代碼,大夥好好了解下,代碼AC過的:

都說了是并查集的題目,是以并查集的做法先來一遍,現在小弟來種不需要并查集的方法!!!!!!

直接上代碼!!!!!!同AC過的:

具體為什麼???!!!自個兒了解去吧!!!!!!

好啦!!!!!!

鹵煮不容易啊!!!!!!在這麼傷感的日子(520)裡還要寫題解造福大夥,你們是不是覺得我好偉大!!!!!!O(∩_∩)O哈哈~

還是那句話,如果發現bug,還請指出,不勝感激,晚安啦!!!!!!