1021 Deepest Root

DFS+BFS: 

#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n;
vector<int>u,v,f,ne;
vector<bool>book;
vector<int>ml;
int c = 0, mle=0;
void cbfs(int bh) {
	c++;
	int i;
	queue<int>r;
	r.push(bh);
	while (!r.empty()) {
		book[r.front()] = true;
		for (i = f[r.front()]; i != -1; i = ne[i]) {
			if (book[v[i]])
				continue;
			r.push(v[i]);
		}
		r.pop();
	}
	return;
}
void dfs(int cur, int l) {
	int i;
	mle = (mle >= l) ? mle : l;
	for (i = f[cur]; i != -1; i = ne[i]) {
		if (!book[v[i]]) {
			book[v[i]] = true;
			dfs(v[i], l + 1);
			book[v[i]] = false;
		}
    }
	return;
}
void mldfs() {
	int i, j;
	for (i = 1; i <= n; i++) {
		mle = 0;
		book= vector<bool>(n + 1, false);
		book[i] = true;
		dfs(i,0);
        ml[i] = mle;
	}
	return;
}
int main() {
	int i,j=0;
	cin >> n;
    f = vector<int>(n + 1, -1);
	book = vector<bool>(n + 1, false);
	ml = vector<int>(n + 1);
	for (i = 1; i <= n - 1; i++) {
		int x1, x2;
		cin >> x1 >> x2;
		u.push_back(x1);
		v.push_back(x2);
		ne.push_back(f[x1]);
		f[x1] = j;
		j++;
		u.push_back(x2);
		v.push_back(x1);
		ne.push_back(f[x2]);
		f[x2] = j;
		j++;
	}
	for (i = 1; i <= n; i++) {
		if (!book[i])
			cbfs(i);
	}
    if(c!=1)
		printf("Error: %d components", c);
	else {
		mldfs();
		for (i = 1; i <= n; i++) {
			if (ml[i] == mle)
				cout << i << endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值