2019牛客暑期多校训练营(第四场)A-meeting

题目链接:A-meeting
题意:给你n个点的图,有k个人在k个点上,他们要聚到一个点,求所有人都聚到一起的最短时间
题解:这道题其实就是找k个人中最远的2个点,他们距离的一半就是答案

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int Size = 1e5 + 5;

int n, m;
int f[Size][25], deep[Size];
int a[Size];
vector <int> vec[Size];

void dfs(int u) {
	deep[u] = deep[f[u][0]] + 1;
	for (int i = 0; f[u][i]; i++) f[u][i + 1] = f[f[u][i]][i];
	for (int i = 0; i < vec[u].size(); i++) {
		int v = vec[u][i];
		if (!deep[v]) f[v][0] = u, dfs(v);
	}
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i < n; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		vec[x].push_back(y);
		vec[y].push_back(x);
	}
	for (int i = 0; i < m; i++) scanf("%d", a + i);
	dfs(1);
	int Max = 0;
	int pd = 0;
	for (int i = 0; i < m; i++) {
		if (deep[a[i]] > Max) {
			Max = deep[a[i]];
			pd = a[i];
		}
	}
	memset(deep, 0, sizeof(deep));
	for (int i = 0; i <= n; i++) {
		for (int j = 0; j < 25; j++) f[i][j] = 0;
	}
	dfs(pd);
	Max = 0;
	for (int i = 0; i < m; i++) Max = max(Max, deep[a[i]]);
	cout << Max / 2 << endl;
	return 0;
}

你可能感兴趣的:(图论)