1021 Deepest Root (25point(s)) Easy only once

基本思想:

雷同的并查集;

关键点:

无;

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector> 
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
using namespace std;

int n;
vector<int>father;
vector<vector<int>>matrix;
vector<int>fin;
int mly = 0;

void init() {
	father.resize(n + 1);
	for (int i = 0; i < father.size(); i++)
		father[i] = i;
}

int findfather(int nn) {
	int temp=nn;
	while (father[nn] != nn) {
		nn = father[nn];
	}
	while (temp != father[temp]) {
		int a = temp;
		temp = father[temp];
		father[a] = nn;
	}
	return nn;
}

void unionfather(int a, int b) {
	int aa = findfather(a);
	int bb = findfather(b);
	if (aa != bb) {
		father[aa] = bb;
	}
}

int cnt() {
	int c = 0;
	for (int i = 1; i <= n; i++) {
		if (father[i] == i) {
			c++;
		}
	}
	return c;
}

int func() {
	for (int i = 1; i <= n; i++) {
		for (int j = 0; j < matrix[i].size(); j++) {
			unionfather(i, matrix[i][j]);
		}
	}
	return cnt();
}

int bfs(int st) {
	int layer = 0;
	vector<bool>vis(n+1);
	fill(vis.begin(), vis.end(), false);
	queue<int>q;
	vis[st] = true;
	q.push(st);
	while (!q.empty()){
		//cout << layer << endl;
		layer++;
		int size = q.size();
		for (int i = 0; i < size; i++) {
			int index = q.front();
			q.pop();
			for (int j = 0;j< matrix[index].size(); j++) {
				if (!vis[matrix[index][j]]) {
					vis[matrix[index][j]] = true;
					q.push(matrix[index][j]);
				}
			}
		}
	}
	return layer;
}

int main() {
	scanf("%d", &n);
	int a, b;
	matrix.resize(n + 1);
	init();
	for (int i = 0; i < n - 1; i++) {
		scanf("%d%d", &a, &b);
		matrix[a].push_back(b);
		matrix[b].push_back(a);
	}
	int c = func();
	if (c != 1) {
		cout << "Error: "<<c<<" components" << endl;
		return 0;
	}
	for (int i = 1; i <= n; i++) {
		int l = bfs(i);
		if (l > mly) {
			mly = l;
			fin.resize(0);
			fin.push_back(i);
		}
		else if (l == mly) {
			fin.push_back(i);
		}
	}
	for (auto ele : fin) {
		cout << ele << endl;
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/songlinxuan/p/12315630.html