国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

1021. Deepest Root 解析

2019-11-11 01:59:32
字體:
來源:轉載
供稿:網友

DFS的改版 需要依次對每個頂點分別進行DFS然后求深度做大的幾個頂點。

理清思路應該可以出來。

#include <iostream>#include <vector>#define Max 10010using namespace std;vector <int> g[Max];vector <bool> isVisit;vector <int> depth;vector <int> Root;int N;int ThisDepth = 1;int MaxDepth = 1;void DFS(int st ,int depth){ //st起點//	cout << "st: " << st << "d; " << depth << endl;	isVisit[st] = true;	ThisDepth = depth;	if (ThisDepth > MaxDepth)		MaxDepth = ThisDepth;	for (int i = 0; i < g[st].size(); i++) {		int v = g[st][i];		if (!isVisit[v]) {			 DFS(v, depth + 1);		}	}}int DFSTrave() {	int num = 0;//判斷是否聯通	int temp;	for (int j = 0; j < N ; j++) { //依次以各頂點為起點//		cout << " ----- " << j+1 << "-------" << endl;		ThisDepth = 1; MaxDepth = 1;		isVisit.clear();		isVisit.resize(N, false);		num = 1;		DFS(j, 1);		depth.push_back(MaxDepth);//保存深度		for (int i = 0; i < N ; i++) { //是否聯通			if (!isVisit[i]) {				num++;				DFS(i, 1);			}		}		if (num != 1)			return num;	}	return num;}void FindMax() {	int max = 0;	for (int i = 0; i < depth.size(); i++) {//		cout << depth[i] << endl;		if (depth[i] > max) {			max = depth[i];			Root.clear();			Root.push_back(i);		}		else if (depth[i] == max) {			Root.push_back(i);		}	}}int main() {	int Head, Tail;	cin >> N;	for (int i = 0; i < N-1; i++) {//N-1 行		cin >> Head >> Tail;//		cout << Head << " " << Tail << endl;		Head--; Tail--;//歸0		g[Head].push_back(Tail);		g[Tail].push_back(Head);	}#ifdef _DEBUG	for (int i = 0; i < N -1; i++) {		cout << "-----j: " << i+1 << "-------" << endl;		for (int j = 0; j < g[i].size(); j++) {			cout << g[i][j] +1 << endl;		}	}#endif	isVisit.resize(N, false);	int n = DFSTrave();	FindMax();#ifdef _DEBUG	cout << "depth" << endl;	for (int i = 0; i < depth.size(); i++) {		cout << depth[i] << endl;	}	cout << "----------" << endl;#endif		if (n != 1) {		cout << "Error: " << n << " components" << endl;	}	else {		for (int i = 0; i < Root.size(); i++) {			cout << Root[i]+1 << endl;		}	}		system("pause");	return 0;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 科技| 肥乡县| 黔江区| 天台县| 阳朔县| 资中县| 兴义市| 沙雅县| 浦东新区| 盐源县| 台中市| 乌拉特中旗| 兰西县| 乳源| 靖宇县| 阳东县| 温泉县| 内丘县| 芮城县| 白玉县| 微山县| 阿巴嘎旗| 绍兴市| 江孜县| 石家庄市| 嵊泗县| 甘泉县| 武清区| 成安县| 杭锦旗| 资阳市| 宁南县| 桃园县| 宣武区| 昌邑市| 陆丰市| 泰安市| 万州区| 金山区| 麻栗坡县| 若羌县|