Is It A Tree?

Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

Submit Status

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. 

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

6 8  5 3  5 2  6 4
5 6 0 0 8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0 3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1

Sample Output

Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree. 题意:给定一定关系,判断其是否是一棵树,注意,空树也是一棵树,不能有成环的情况,不能是森林,不能有入度为2的节点。
下面给出两种思路:
1,并查集:维护一个森林 每输入一组关系(边)的时候,将这两个点连起来看做一棵树,如果可以将其合并到其他的树上的话就将其合并,并且树的总数目加1;
(注意: 只有当第二个端点值在其他树上是根节点的时候才能合并仍保持是一棵树,及从第一个端点指向第二个端点的时候会保证不会出现入度为2的点)
如果不满足合并条件的时候就将定义的树的总数加1,中间过程有可能再将这两棵树连起来,所有操作完成后,统计树的个数,要是树的棵树大于1的话则所给点不能构成一棵树
注意要排除自成环的情况,和空树的情况。
2,dfs:
 将所有的边用链接表的方式存起来,当按照正常的顺序扫描一遍的时候如果是一个符合条件的树的话就不会存在一个点被访问两次,即扫描的时候不会出现visit数组被标记为走过的情况
而且当以任一点为开始扫描完一遍的时候不存在没有扫描过的点,因为不存在森林。
这里同样要考虑空树的情况。
 /**
---------------------------------------------------
HuHanwu
2012-7-12
并查集快速判断每次输入是破坏树的性质
时间复杂度: o(n) n为节点的个数
---------------------------------------------------
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAXN 1000002 int p[MAXN]; //存放父亲节点 只要存在父亲节点则此节点一存在某棵树中
int find(int x){ return p[x]==x ? x :(p[x]=find(p[x]));} //查找父亲节点并 压缩路径 int main()
{
int a,b,tree_num,t=,father_a,father_b,TF; //tree_num 保存当前的树的棵数
while(~scanf("%d%d",&a,&b) && (a>=||b>=))
{
tree_num=TF=;
if(a==)
{
printf("Case %d is a tree.\n",++t);
continue;
}//空树也是一棵树
if(a==b)
TF=;//不能成环
else
{
memset(p,,sizeof(p)); //用 0 初始化所有节点的父亲节点
p[a]=p[b]=a;
}
while(~scanf("%d%d",&a,&b) && a!=)
{
if(TF== ) // 只要已经判断出该森林已经不是树
continue;
if(p[b]!=) // b节点已经存在
{
father_b=find(b);
if(b!=father_b) // b 节点不是树根就不可以连成一棵树
{
TF=;
continue;
}
else//下面都是当b 为树根的情况
{
if(p[a]!=) // a b 节点都存在则树的的棵数-1
{
p[b]=find(a);//将两棵树连起来,只有当b是父节点的时候才可以这么连
tree_num--;
}
else //a 节点不存在 而 b 节点存在
p[b]=p[a]=a;
}
}
else
{
if(p[a]==) // a b 节点都不存在则树的棵数+1
{
p[a]=p[b]=a;
tree_num++;
}
else //a 节点存在 而 b 节点不存在
p[b]=find(a);
}
}
printf("Case %d ",++t);
if(TF==)
{
printf("is not a tree.\n");
continue;
}
if(tree_num==) // 树的棵数是否为1
printf("is a tree.\n");
else
printf("is not a tree.\n");
}
return ;
}

下面给出dfs代码,其中用链表存放边

 #include <cstdio>
#include <map>
#include <cstring>
using namespace std;
#define N 50005 int head[N];
struct Edge{
int v, next;
}edge[N*];
int Ecnt; void init()
{
Ecnt = ;
memset(head, -, sizeof(head));
} void add(int u, int v)
{
edge[Ecnt].v = v;
edge[Ecnt].next = head[u];
head[u] = Ecnt++;
} bool visited[N];
bool dfs(int u)
{
for(int i = head[u]; i != -; i = edge[i].next)
{
int v = edge[i].v;
if(visited[v]) return false;
visited[v] = ;
int res = dfs(v);
if(res == false) return false;
}
return true;
} struct Node {
int s, t;
}node[N]; map<int, int>mp; int in[N];
int main()
{
int s, t, cas = ;
while(~scanf("%d %d", &s, &t))
{
cas++;
if(s == && t == ){
printf("Case %d is a tree.\n", cas);
continue;
}
if(s < && t < ) break;
int c = ;
node[c].s = s, node[c++].t = t;
while(~scanf("%d %d", &s, &t), s||t)
node[c].s = s, node[c++].t = t; mp.clear();
int n = ;//结点总数
for(int i = ; i < c; i++)
{
s = node[i].s, t = node[i].t;
if(mp.find(s) == mp.end()) mp[s] = n++;
if(mp.find(t) == mp.end()) mp[t] = n++;
node[i].s = mp[s];
node[i].t = mp[t];
}
init();
memset(in, , sizeof(in));
for(int i = ; i < c; i++)
{
s = node[i].s, t = node[i].t;
add(s, t);
in[t]++;
}
bool ans = true;
int root = -;
for(int i = ; i < n; i++)
{
if(in[i] == )
{
if(root == -) root = i;
else ans = false;
}
}
if(ans == false || root == -)
{
printf("Case %d is not a tree.\n", cas);
ans = false;
continue;
}
memset(visited, , sizeof(visited));
visited[root] = ;
ans = dfs(root);
if(ans == false)
{
printf("Case %d is not a tree.\n", cas);
ans = false;
continue;
}
for(int i = ; i < n; i++)
if(!visited[i])
{
printf("Case %d is not a tree.\n", cas);
ans = false;
break;
}
if(ans)printf("Case %d is a tree.\n", cas);
}
}

Is It A Tree?(并查集)(dfs也可以解决)的更多相关文章

  1. F2 - Spanning Tree with One Fixed Degree - 并查集+DFS

    这道题还是非常有意思的,题意很简单,就是给定一个图,和图上的双向边,要求1号节点的度(连接边的条数)等于K,求这棵树的生成树. 我们首先要解决,如何让1号节点的度时为k的呢???而且求的是生成树,意思 ...

  2. 第46届ICPC澳门站 K - Link-Cut Tree // 贪心 + 并查集 + DFS

    原题链接:K-Link-Cut Tree_第46屆ICPC 東亞洲區域賽(澳門)(正式賽) (nowcoder.com) 题意: 要求一个边权值总和最小的环,并从小到大输出边权值(2的次幂):若不存在 ...

  3. 1021.Deepest Root (并查集+DFS树的深度)

    A graph which is connected and acyclic can be considered a tree. The height of the tree depends on t ...

  4. 树上统计treecnt(dsu on tree 并查集 正难则反)

    题目链接 dalao们怎么都写的线段树合并啊.. dsu跑的好慢. \(Description\) 给定一棵\(n(n\leq 10^5)\)个点的树. 定义\(Tree[L,R]\)表示为了使得\( ...

  5. Codeforces_764_C. Timofey and a tree_(并查集)(dfs)

    C. Timofey and a tree time limit per test 2 seconds memory limit per test 256 megabytes input standa ...

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

    Is It A Tree? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) To ...

  7. HDU 1232 并查集/dfs

    原题: http://acm.hdu.edu.cn/showproblem.php?pid=1232 我的第一道并查集题目,刚刚学会,我是照着<啊哈算法>这本书学会的,感觉非常通俗易懂,另 ...

  8. Is It A Tree?(并查集)

    Is It A Tree? Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 26002   Accepted: 8879 De ...

  9. CF109 C. Lucky Tree 并查集

    Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal re ...

随机推荐

  1. CSS height:100%无效

    本文同时发表在https://github.com/zhangyachen/zhangyachen.github.io/issues/38 浏览器根本就不计算内容的高度,除非内容超出了视窗范围(导致滚 ...

  2. Python图片爬虫

    1.今天给大家介绍自己写的一个图片爬虫,说白了就是从网页自动上下载需要的图片 2.首先选取目标为:http://www.zhangzishi.cc/涨姿势这个网站如下图,我们的目标就是爬取该网站福利社 ...

  3. 编译Twitter的Heron时一直报错“heron/bazel_configure.py", line 25, in <module> import semver ImportError: No module named semver”如何处理。

    今天编译heron的时候,从官方git到的源码bazel_configure的时候一直报错如下: Traceback (most recent call last): File , in <mo ...

  4. docker 保存 加载(导入 导出镜像

    tensorflow 的docker镜像很大,pull一次由于墙经常失败.其实docker 可以将镜像导出再导入. 保存加载(tensorflow)镜像 1) 查看镜像 docker images 如 ...

  5. 我 对jvm 创建线程的一些了解

    1.jvm 每创建一个线程都会对应产生一个该线程的虚拟机栈,栈大小通过-Xss参数来设置,JDK1.5之后默认为1M 2.JVM创建线程需要内存,但这部分内存不使用堆内存(毕竟JVM虚拟机栈).对于3 ...

  6. Django_form

    Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 1.创建Form类 # 创建一个类 from ...

  7. CSS学习之首页简单布局

    作为一个PHPer,在前端方面javascript.jquery这些的日常工作还搞的定.可对于div+css这些东西可就头疼了,所以现在开始学习CSS 跟着燕十八的教程开始从最基础学起,首先练习一个简 ...

  8. LeetCode题目总结(一)

    我的代码在github上,https://github.com/WINTERFELLS/LeetCode-Answers 这里只提供个人的解题思路,不一定是最好的. Problems1-20 寻找两个 ...

  9. SignalR的另类实现技巧

    很久之前发表过一篇名为<通过三个DEMO学会SignalR的三种实现方式>的文章,在那篇文章里面详细介绍了在WEB应用下的常用SignalR实现方法,而今天我们来利用SignalR来实现其 ...

  10. Hibernate学习笔记(6)---Criteria接口

    Criteria接口 Criteria查询通过面相对向的设计,将数据查询条件封装为一个对象.在hibernate执行时会把criteria指定的查询恢复相应的sql语句. 条件查询 Criteria ...