博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hnsd11348tree(并查集)
阅读量:5275 次
发布时间:2019-06-14

本文共 2360 字,大约阅读时间需要 7 分钟。

Problem description

A graph consists of a set of vertices and edges between pairs of vertices. Two vertices are connected if there is a path (subset of edges) leading from one vertex to another, and a connected component is a maximal subset of vertices that are all connected to each other. A graph consists of one or more connected components.

A tree is a connected component without cycles, but it can also be characterized in other ways. For example, a tree consisting of n vertices has exactly n-1 edges. Also, there is a unique path connecting any pair of vertices in a tree.

Given a graph, report the number of connected components that are also trees.

Input

The input consists of a number of cases. Each case starts with two non-negative integers n and m, satisfying n ≤ 500 and m ≤ n(n-1)/2. This is followed by m lines, each containing two integers specifying the two distinct vertices connected by an edge. No edge will be specified twice (or given again in a different order). The vertices are labelled 1 to n. The end of input is indicated by a line containing n = m = 0.

Output

For each case, print one of the following lines depending on how many different connected components are trees (T > 1 below):

Case x: A forest of T trees.	Case x: There is one tree.	Case x: No trees.

x is the case number (starting from 1).

Sample Input
6 31 22 33 46 51 22 33 44 55 66 61 22 31 34 55 66 40 0
Sample Output
Case 1: A forest of 3 trees.Case 2: There is one tree.Case 3: No trees.
#include
int fath[505],cycl[505],k,n;void setfirst(){ k=n; for(int i=1;i<=n;i++) { fath[i]=i; cycl[i]=0; }}int find_fath(int x){ if(x!=fath[x]) fath[x]=find_fath(fath[x]); return fath[x];}void setTree(int a,int b){ a=find_fath(a); b=find_fath(b); if(cycl[b]&&cycl[a]) return ; k--; if(a!=b) { if(cycl[a]) fath[b]=a; else fath[a]=b; } else cycl[a]=1;}int main(){ int a,b,m,t=1; while(scanf("%d%d",&n,&m)>0&&m+n!=0) { setfirst(); while(m--) { scanf("%d%d",&a,&b); setTree(a,b); } printf("Case %d: ",t++); if(k>1)printf("A forest of %d trees.\n",k); if(k==1)printf("There is one tree.\n"); if(k==0)printf("No trees.\n"); }}
 

转载于:https://www.cnblogs.com/suncoolcat/p/3297240.html

你可能感兴趣的文章
android:scaleType属性
查看>>
shell脚本
查看>>
Upload Image to .NET Core 2.1 API
查看>>
【雷电】源代码分析(二)-- 进入游戏攻击
查看>>
Linux中防火墙centos
查看>>
如何设置映射网络驱动器的具体步骤和方法
查看>>
centos下同时启动多个tomcat
查看>>
Leetcode Balanced Binary Tree
查看>>
[JS]递归对象或数组
查看>>
linux sed命令
查看>>
湖南多校对抗赛(2015.03.28) H SG Value
查看>>
hdu1255扫描线计算覆盖两次面积
查看>>
hdu1565 用搜索代替枚举找可能状态或者轮廓线解(较优),参考poj2411
查看>>
程序存储问题
查看>>
优雅地书写回调——Promise
查看>>
AX 2009 Grid控件下多选行
查看>>
PHP的配置
查看>>
Struts框架----进度1
查看>>
Round B APAC Test 2017
查看>>
MySQL 字符编码问题详细解释
查看>>