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条件的时候等于是"==",我有好几次都只写了一个=导致检查了半天错误,大家切记。

相关推荐
DARLING Zero two♡3 分钟前
C++寻位映射的奇幻密码:哈希
c++·哈希算法
gyeolhada11 分钟前
2025蓝桥杯JAVA编程题练习Day8
java·数据结构·算法·蓝桥杯
freyazzr19 分钟前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
AI technophile26 分钟前
OpenCV计算机视觉实战(6)——经典计算机视觉算法
opencv·算法·计算机视觉
qq_5845989228 分钟前
day30python打卡
开发语言·人工智能·python·算法·机器学习
zhangpeng45554794030 分钟前
C++--综合应用-演讲比赛项目
开发语言·c++·算法
霜羽689241 分钟前
【数据结构篇】排序1(插入排序与选择排序)
数据结构·算法·排序算法
啊我不会诶42 分钟前
CF每日4题(1300-1400)
开发语言·c++·算法
JK0x071 小时前
代码随想录算法训练营 Day51 图论Ⅱ岛屿问题Ⅰ
算法·深度优先·图论
freyazzr1 小时前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论