1021. Deepest Root 解析
来源:互联网 发布:js 获取鼠标位置 编辑:程序博客网 时间:2024/06/06 01:16
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--;//归0g[Head].push_back(Tail);g[Tail].push_back(Head);}#ifdef _DEBUGfor (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;}}#endifisVisit.resize(N, false);int n = DFSTrave();FindMax();#ifdef _DEBUGcout << "depth" << endl;for (int i = 0; i < depth.size(); i++) {cout << depth[i] << endl;}cout << "----------" << endl;#endifif (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;}
0 0
- 1021. Deepest Root 解析
- 1021. Deepest Root (25)
- 1021. Deepest Root
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- PAT 1021. Deepest Root
- PAT 1021. Deepest Root
- 1021. Deepest Root
- 1021. Deepest Root (25)
- pat 1021. Deepest Root
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021.Deepest Root
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- MySql数据库语法对比
- js取整数四舍五入
- 详解基于java的Socket聊天程序——客户端(附demo)
- jpa多条件查询重写Specification的toPredicate方法
- 16.下拉菜单的样式
- 1021. Deepest Root 解析
- Java中弹出对话框中的几种方式
- 1025. PAT Ranking (25)
- Android保证service不被杀掉-增强版: 进程保活(根据用户需求慎用)
- mysql 重设root 密码
- Codevs 1242 布局 2005年USACO(差分约束)
- iOS报错:108 duplicate symbols for architecture arm64
- 详解基于java的Socket聊天程序——服务端(附demo)
- mysql编译安装MySQL5.5.32