PAT1021(dfs 连通分量)
A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes' numbers.
Output Specification:
For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print "Error: K components" where K is the number of connected components in the graph.
Sample Input 1:
5 1 2 1 3 1 4 2 5
Sample Output 1:
3 4 5
Sample Input 2:
5 1 3 1 4 2 5 3 4
Sample Output 2:
Error: 2 components
题目大意:给你一个图,判断这个图能不能构成树,不能构成输出它的连通分量。能构成树,输出以哪些节点为根树的高度最高。
首先通过dfs寻找连通分量的个数,如果不为1,输出无法构成树。
如果为1:两遍dfs找最高的点:
首先以某个点为根,进行dfs(),得到高度最高的点。再从这些点中随机选择一个点再进行dfs,保存高度最高的点,两次遍历的并集即为答案。
代码如下:
#include<iostream> #include<cstdio> #include<vector> #include<cstring> #include<set> using namespace std; vector<int>v[10010]; bool vis[10010]; vector<int>temp; set<int>s; int maxheight; void dfs(int n,int depth) { if(maxheight<depth) { maxheight=depth; temp.clear(); temp.push_back(n); } else if(depth==maxheight) { temp.push_back(n); } vis[n]=1; for(int i=0;i<v[n].size();i++) { if(!vis[v[n][i]]) { dfs(v[n][i],depth+1); } } } int main() { int n,a,b; scanf("%d",&n); memset(vis,0,sizeof(vis)); for(int i=1;i<=n-1;i++) { scanf("%d%d",&a,&b); v[a].push_back(b); v[b].push_back(a); } int cnt=0,s1; for(int i=1;i<=n;i++) { maxheight=0; if(!vis[i]) { dfs(i,1); for(int j=0;j<temp.size();j++) { cout<<temp[j]<<endl; s.insert(temp[j]); if(j==0) s1=temp[j]; } cnt++; } } if(cnt!=1) printf("Error: %d components\n",cnt); else { memset(vis,0,sizeof(vis)); dfs(s1,1); for(int i=0;i<temp.size();i++) s.insert(temp[i]); set<int>:: iterator it; it=s.begin(); for(it;it!=s.end();it++) printf("%d\n",*it); } }