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

相关推荐
十五年专注C++开发14 分钟前
Qt .pro配置gcc相关命令(三):-W1、-L、-rpath和-rpath-link
linux·运维·c++·qt·cmake·跨平台编译
车队老哥记录生活25 分钟前
【MPC】模型预测控制笔记 (3):无约束输出反馈MPC
笔记·算法
Cai junhao38 分钟前
【Qt】Qt控件
开发语言·c++·笔记·qt
uyeonashi1 小时前
【QT系统相关】QT网络
开发语言·网络·c++·qt
地平线开发者1 小时前
BEV 感知算法评价指标简介
算法·自动驾驶
不过四级不改名6771 小时前
用c语言实现简易c语言扫雷游戏
c语言·算法·游戏
我命由我123452 小时前
嵌入式 STM32 开发问题:烧录 STM32CubeMX 创建的 Keil 程序没有反应
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式
筏.k3 小时前
C++: 类 Class 的基础用法
android·java·c++
C++ 老炮儿的技术栈3 小时前
手动实现strcpy
c语言·开发语言·c++·算法·visual studio
一条叫做nemo的鱼3 小时前
从汇编的角度揭开C++ this指针的神秘面纱(下)
java·汇编·c++·函数调用·参数传递