POJ 1308 Is It A Tree?(并查集)
2015-12-29 17:47
399 查看
Description
给出一些几点的连接情况,判断这些节点能否组成一棵树
Input
多组用例,每组用例每次输入两个整数a和b表示有一条a指向b的边,以0 0结束一组用例的输入,以-1 -1结束所有输入
Output
对于每组用例,判断这些节点能否组成一棵树
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.
Solution
简单并查集,不知道输入节点的编号所以先开一个标记数组标记每个编号的节点是否出现过,然后注意几种特殊情况
1.(0 0) 空树是一棵树
2.1 1 0 0 自己指向自己,不是树
3.1 2 2 1 0 0 儿子指向父亲,不是树
4.1 2 1 2 0 0 重边,不是树
5.1 2 4 5 0 0 森林,不是树
Code
给出一些几点的连接情况,判断这些节点能否组成一棵树
Input
多组用例,每组用例每次输入两个整数a和b表示有一条a指向b的边,以0 0结束一组用例的输入,以-1 -1结束所有输入
Output
对于每组用例,判断这些节点能否组成一棵树
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.
Solution
简单并查集,不知道输入节点的编号所以先开一个标记数组标记每个编号的节点是否出现过,然后注意几种特殊情况
1.(0 0) 空树是一棵树
2.1 1 0 0 自己指向自己,不是树
3.1 2 2 1 0 0 儿子指向父亲,不是树
4.1 2 1 2 0 0 重边,不是树
5.1 2 4 5 0 0 森林,不是树
Code
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> using namespace std; #define maxn 111 int par[maxn]; int mark[maxn]; void init(int n) { for(int i=0;i<n;i++) { par[i]=i; mark[i]=0; } } int find(int x) { if(par[x]==x) return x; return par[x]=find(par[x]); } void unite(int x,int y) { x=find(x); y=find(y); if(x==y) return; par[y]=x; } int main() { int x,y,root,res=1; while(~scanf("%d%d",&x,&y),~x) { if(x==0&&y==0) { printf("Case %d is a tree.\n",res++); continue; } bool flag=1; init(maxn); mark[x]=mark[y]=1; root=x; if(x==y)flag=0; else unite(x,y); while(scanf("%d%d",&x,&y),x||y) { mark[x]=mark[y]=1; if(find(x)==find(y))flag=0; else unite(x,y); } for(int i=1;i<maxn;i++) if(mark[i]&&find(i)!=find(root)) { flag=0; break; } if(flag)printf("Case %d is a tree.\n",res++); else printf("Case %d is not a tree.\n",res++); } return 0; }
相关文章推荐
- Android Studio 多渠道打包, 自定义APK名称
- Linux下安装Apache httpd server
- HTTPS工作原理
- EasyPHP-2.0b1+ Mantis-1.1.0安装及技巧
- 2-Twenty third Scrum Meeting-20151229
- MFC的picture控件静态动态加载位图
- golang快速安装示例
- CentOS7.2 安装redis 3.0.6集群
- Sql Server利用游标批量清空数据表
- 常用知识点
- ajax当状态为"json"时,服务端返回回来若不是json格式则不执行操作,切记。。。
- 一些很好的linux站点
- Centos7中安装Tomcat服务器
- arm指令移位指令
- 虚拟化
- 创建git repository的脚本
- JVM1.6 GC详解
- 【扩展欧几里得】Bzoj 1407: [Noi2002]Savage
- 合并文件的FileChannel方式
- linux mysql详尽版