1021. Deepest Root (25)
来源:互联网 发布:控制台运行java程序 编辑:程序博客网 时间:2024/05/01 05:49
开始用各个叶节点dfs遍历,找最大deep,运行超时,然后评论里发现个方法,挺赞
https://www.nowcoder.com/questionTerminal/f793ad2e0c7344efa8b6c18d10d4b67b
#include<iostream>#include<algorithm>#include<vector>#define MAX_V 10002using namespace std;vector<int> arc[MAX_V];//相等于邻接矩阵vector<int> P;//输出的数组int dis[MAX_V];//相对于root距离int N,dis_max=0;//相对于root最大距离bool visited[MAX_V] = {0};void dfs(int index){ if (dis_max < dis[index]) dis_max = dis[index]; for (auto x : arc[index]) { if (visited[x] == NULL) { dis[x] = dis[index] + 1; visited[x] = true; dfs(x); } }}int main(){ cin >> N; for (int t = 1;t < N;t++) { int i, j; cin >> i >> j; arc[i].push_back(j); arc[j].push_back(i); } int count=0; for (int t = 1;t <= N;t++) { if (visited[t] == false) { dis[t] = 0; visited[t] = true; dfs(t); count++; } } if (count != 1) cout << "Error: " << count << " components" << endl; else { for (int t = 1;t <= N;t++) { if (dis[t] == dis_max) P.push_back(t); visited[t] = false; } visited[P.back()] = true; dfs(P.back()); for (int t = 1;t <= N;t++) { if (find(P.begin(), P.end(), t) == P.end()) if (dis[t] == dis_max) P.push_back(t); } sort(P.begin(), P.end()); for (auto x : P) cout << x << endl; }}
0 0
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 1021. Deepest Root (25)
- 博为峰Java技术文章 ——JavaSE Swing JTabbedPane选项卡面板II
- VS2010下建立MFC程序
- 使用camera、matrix仿即刻APP换一换
- 假期训练—— Repeating Decimals UVA - 202 模拟
- sed 脚本分隔符引起的问题 的问题
- 1021. Deepest Root (25)
- Android源码之ArrayList
- XXX
- Python的charts和Jupyter的使用 使数据可视化 对58同城的爬取
- Bootstrap学习笔记(五)菜单、按钮及导航
- 关于Spring容器的理解
- RecyclerView的用法
- spring data jpa
- php 使用ssh2 操作linux、mysql(模拟阿里云控制台)