1021 Deepest Root (25分)(一个字短!)

1021 Deepest Root (25分)

分析

在深度优先遍历的同时,计算连通分量的个数,以及最大深度的节点,加入set中。
第二次选第一次遍历得到的节点中的其中一个,开始深度优先遍历,得到的深度最深的节点也加入set中,从而得到所有的可以作为高度最大的树的根节点的节点。
提供一个测试用例
5
1 2
2 3
2 4
4 5

代码

#include<iostream>
#include<vector>
#include<set>
using namespace std;
int n, a, b, maxdepth = 1, marked[10010], components = 0;
vector<int> tree[10010];
set<int> s, ss;
void dfs(int k, int depth) {
 marked[k] = 1;
 if (depth > maxdepth) {
  maxdepth = depth;
  s.clear();
 }
 if (depth == maxdepth)s.insert(k);
 for (int i = 0; i < tree[k].size(); ++i)
  if (!marked[tree[k][i]])
   dfs(tree[k][i], depth + 1);
}
int main() {
 scanf("%d", &n);
 for (int i = 0; i < n - 1; ++i) {
  scanf("%d %d", &a, &b);
  tree[a].push_back(b);
  tree[b].push_back(a);
 }
 for (int i = 1; i <= n; ++i)
  if (!marked[i]) {
   dfs(i, 1);
   ++components;
  }
 if (components != 1) {
  printf("Error: %d components", components);
  return 0;
 }
 ss = s;
 s.clear();
 maxdepth = 1;
 fill(marked, marked + 10010, 0);
 dfs(*ss.begin(), 1);
 for (auto it : s)ss.insert(it);
 for (auto it : ss)printf("%d\n", it);
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值