数据结构 并查集 Poj 1308
2016-08-07 17:01
323 查看
#include <cstdio> #include <math.h> #include <cstring> int parent[100005]; int vis[100005]; int n,m;//用来记录 点的个数 为了判断是否有环 n为点 m为边 int flag;//是否输入的两个数字已经是 树上的点 int find(int x) { if(x!=parent[x]) { return parent[x]=find(parent[x]); } else return x; } void into() { for(int i=0;i<100005;i++) { parent[i]=i; vis[i]=0; } n=0;m=0;flag=0; } int main() { int x,y; int cas=1; into(); while(scanf("%d%d",&x,&y)!=EOF && x!=-1 &&y!=-1) { if(x==0 && y==0) { printf("Case %d is ",cas++); //flag 说明 已经在一棵树上了, 重复 //n-1==m 没有环 //n==0 坑点,没有点也是树 if(!flag && (n-1==m || n==0)) printf("a tree.\n"); else printf("not a tree.\n"); into(); continue;//一定要跳出去 } int px=find(x);int py=find(y); if(!vis[x]) n++; vis[x]=1; if(!vis[y]) n++; vis[y]=1; if(px!=py) { parent[py]=px; m++;// 不在一个树上 m为边 } else flag=1; } return 0; }
相关文章推荐
- 浅析数据结构与算法11--哈希表
- 浅析数据结构与算法12--无向图相关算法基础
- 浅析数据结构与算法5--优先队列与堆排序
- 浅析数据结构与算法4--快速排序
- 浅析数据结构与算法3--合并排序
- 浅析数据结构与算法2--基本排序算法
- 浅析数据结构与算法1--栈和队列
- 数据结构实验之查找七:线性之哈希表
- 浅析数据结构与算法6--符号表及其基本实现
- 浅析数据结构与算法10--平衡查找树之B树
- 浅析数据结构与算法9--平衡查找树之红黑二叉查找树
- 浅析数据结构与算法8--平衡查找树之2-3查找树
- 数据结构实验之查找五:平方之哈希表
- 浅析数据结构与算法7--二叉查找树 及Java实现
- SDUT 3377 数据结构实验之查找五:平方之哈希表
- 数据结构中常见经典算法
- 【HDU5808 BestCoder Round 86E】【时间排序 树状数组计数 bitsetDP 或分治】Price List Strike Back 距离范围、区间范围商店购物 使得价值和恰为m
- 数据结构实验之查找六:顺序查找
- 数据结构 排序(快速排序)
- 数据结构实验之查找四:二分查找