【PAT A1021】Deepest Root

在這裏插入圖片描述
思路
從每個節點依次構樹,選最大者就好了(height數組記錄每個節點所構樹的高度),如果在構樹的過程中有節點沒有訪問到,說明不連通,此時在沒有訪問的節點處再次dfs構樹,依次下去即可得到連通分支個數。

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

int N, visited[10010] = {0}, height[10010];
vector<int> G[10010];

int dfs(int i){
	int h = 0;
	visited[i] = 1;
	for(int j = 0; j < G[i].size(); j++){
		if(visited[G[i][j]] == 0){
			//將高度修改爲自己後代的最高者
			h = max(dfs(G[i][j]), h);
		}
	}
	return h + 1;
}

void getAns(){
	int cnt = 1, maxheight = 0;
	//分別以i爲根構樹
	for(int i = 1; i <= N; i++){
		memset(visited, 0, sizeof(visited));
		height[i] = dfs(i);
		maxheight = max(maxheight, height[i]);
		//如果還有節點沒有被訪問到,說明圖不連通
		for(int j = 1; j <= N; j++){
			if(visited[j] == 0){
				//連通分支數加1
				cnt++;
				dfs(j);//構建連通分支
			}
		}
		//cnt分支數大於1可以直接輸出並結束程序
		if(cnt > 1){
			printf("Error: %d components\n", cnt);
			return;
		}
	}

	for(int i = 1; i <= N; i++)
		if(height[i] == maxheight)
			printf("%d\n", i);
	
}

int main(){
	scanf("%d", &N);
	for(int i = 1; i < N; i++){
		int a, b;
		scanf("%d%d", &a, &b);
		G[a].push_back(b);
		G[b].push_back(a);
	}
	getAns();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章