您的位置:首页 > 其它

Hdu.1325.Is It A Tree?(并查集)

2015-05-19 17:33 429 查看

Is It A Tree?

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 16702 Accepted Submission(s): 3761

[align=left]Problem Description[/align]
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.

#include<stdio.h>
#include<string.h>
const int M = 100000 + 1 ;
int f[M] ;
int path[M] ;
int in[M] ;
bool vis[M] ;

int Union (int x)
{
return x == f[x] ? x : f[x] = Union (f[x]) ;
}
int main ()
{
freopen ("a.txt" , "r" , stdin ) ;
int u , v ;
int cas = 1 ;
while (~ scanf ("%d%d" , &u , &v)) {
if (u < 0 || v < 0) break ;
for (int i = 0 ; i < M ; i ++) f[i] = i ;
memset (vis , 0 , sizeof(vis));
memset (in , 0 , sizeof(in)) ;
int tot = 0 ;
if (!vis[u]) {
vis[u] = 1 ;
path[tot ++] = u ;
}
if (!vis[v]) {
vis[v] = 1 ;
path[tot ++] = v ;
}
in[v] ++ ;
//   printf ("%d ----> %d\n" , u , v);
int x = Union (u) , y = Union (v) ;
f[y] = x ;
if (u != 0 && v != 0) {
while (1) {
scanf ("%d%d" , &u , &v) ;
//    printf ("%d ----> %d\n" , u , v);
if (u == 0 && v == 0) break ;
if (!vis[u]) {
vis[u] = 1 ;
path[tot ++] = u ;
}
if (!vis[v]) {
vis[v] = 1 ;
path[tot ++] = v ;
}
in[v] ++ ;
int x = Union (u) , y = Union (v) ;
f[y] = x ;
}
for (int i = 0 ; i < tot ; i ++) Union (path[i]) ;
//     for (int i = 0 ; i < tot ; i ++) printf ("%d " , path[i]) ; puts ("") ;
//    for (int i = 0 ; i < tot ; i ++) printf ("%d " , in[path[i]]); puts ("") ;
//    for (int i = 0 ; i < tot ; i ++) printf ("%d " , f[path[i]]) ; puts ("") ;
bool flag = 0 ;
int cnt = 0 ;
int father = f[path[0]] ;
for (int i = 1 ; i < tot && !flag; i ++)
if (f[path[i]] != father )
flag = 1 ;

for (int i = 0 ; i < tot && !flag ; i ++) {
if (in[path[i]] > 1) flag = 1 ;
if (in[path[i]] == 0) cnt ++ ;
if (cnt > 1) flag = 1 ;
}
if (cnt == 0) flag = 1 ;
// printf ("flag = %d\n" , flag );
if (flag) printf ("Case %d is not a tree.\n" , cas ++);
else    printf ("Case %d is a tree.\n" , cas ++) ;
}
else printf ("Case %d is a tree.\n" , cas ++) ;
}
return 0 ;
}


View Code
检查入度,和每个结点的祖先。

终于解决了并查集压缩路径的不完全的问题。hahahaha。。。

另外没有结点,也被认为是树。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: