PAT 1021 Deepest Root

个人学习记录,代码难免不尽人意。

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 (≤10 4 ) 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

cpp 复制代码
#include <cstdio>
#include<set>
#include<string>
#include<algorithm>
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
const int maxn=10100;
const int INF=1000000000;
vector<int> G[maxn];
bool visit[maxn]={false};
int height=0;
void dfs(int n){
	visit[n]=true;
	for(int i=0;i<G[n].size();i++){
		if(!visit[G[n][i]]){
			dfs(G[n][i]);
		}
	}
	return;
}
int res=0;
void dfsheight(int n,int height){
	visit[n]=true;
	if(height>res) res=height;
	for(int i=0;i<G[n].size();i++){
		if(!visit[G[n][i]]){
			dfsheight(G[n][i],height+1);
		}
	}
	return;
}
int main(){
  int n;
  scanf("%d",&n);
  for(int i=0;i<n-1;i++){
  	int a,b;
  	scanf("%d %d",&a,&b);
	G[a].push_back(b);
	G[b].push_back(a); 
  }
  int block=0;
  for(int i=1;i<=n;i++){
    if(!visit[i]){
    	dfs(i);
    	block++;
	}
  }
  if(block>1){
  	printf("Error: %d components",block);
  	return 0;
  }
  
  vector<int> v;
  int max=-1;
  for(int i=1;i<=n;i++){

  fill(visit+1,visit+1+n,false);
  	  res=0;
  	  	
  	  dfsheight(i,0);
  	  if(max<res){
  	  	max=res;
  	  	v.clear();
  	  	v.push_back(i);
		}
	   else if(max==res){//这个地方手误写成了max=res卡了好久
	   	v.push_back(i);
	   }
  }
  for(int i=0;i<v.size();i++){
  	printf("%d\n",v[i]);
  }

}

这道题还蛮有意思的,注意题目要求n<=10000,因此不能用邻接矩阵来做必须用邻接表。

其次,题目说给了n-1条边,因此我们可以排除连通块为1且有回路的情况,也就是说可以不用考虑回路。具体做法是先判断连通块是否为1,是则结束,不是则进入下一步dfs处理

各位一定要注意写if条件的时候等于是"==",我有好几次都只写了一个=导致检查了半天错误,大家切记。

相关推荐
青い月の魔女10 分钟前
数据结构初阶---二叉树
c语言·数据结构·笔记·学习·算法
林的快手1 小时前
209.长度最小的子数组
java·数据结构·数据库·python·算法·leetcode
FeboReigns1 小时前
C++简明教程(4)(Hello World)
c语言·c++
FeboReigns1 小时前
C++简明教程(10)(初识类)
c语言·开发语言·c++
千天夜1 小时前
多源多点路径规划:基于启发式动态生成树算法的实现
算法·机器学习·动态规划
zh路西法1 小时前
【C++决策和状态管理】从状态模式,有限状态机,行为树到决策树(二):从FSM开始的2D游戏角色操控底层源码编写
c++·游戏·unity·设计模式·状态模式
从以前1 小时前
准备考试:解决大学入学考试问题
数据结构·python·算法
.Vcoistnt2 小时前
Codeforces Round 994 (Div. 2)(A-D)
数据结构·c++·算法·贪心算法·动态规划
小k_不小2 小时前
C++面试八股文:指针与引用的区别
c++·面试
沐泽Mu2 小时前
嵌入式学习-QT-Day07
c++·qt·学习·命令模式