codeforces 1294F Three Paths on a Tree

本文介绍了一种算法,用于解决在一个无向连通图中寻找三个顶点的问题,这三个顶点之间的边的并集长度最大。通过两次广度优先搜索找到树的直径,再遍历除直径两端点外的其它点,最终确定第三个顶点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:n个点n-1条边的树,找出三个点使得三个点两两之间边的并集最大.

首先找出树的直径..然后遍历一遍其他点

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 7;
int n;
vector<int>g[maxn];
int dist[maxn];
int sum[maxn];
int bfs(int kk)
{
	memset(dist, 0, sizeof(dist));
	dist[kk] = 0;
	queue<int>q;
	q.push(kk);
	int now;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		for (auto x : g[now])
		{
			if (x!=kk&&!dist[x])
			{
				dist[x] = dist[now] + 1;
				q.push(x);
			}
		}
	}
	return now;
}
int main()
{
	while (cin >> n)
	{
		vector<int>a;
		for (int i = 1; i < n; i++)
		{
			int x, y;
			cin >> x >> y;
			g[x].push_back(y);
			g[y].push_back(x);
		}
		int x = bfs(1);
		int y = bfs(x);
		//cout << x << " " << y << endl;
		for (int i = 1; i <= n; i++)sum[i] = dist[i] + dist[y];
		bfs(y);
		int ma = -1, k = 0;
		for (int i = 1; i <= n; i++)
		{
			if (i != x && i != y && sum[i] + dist[i] > ma)
			{
				ma = sum[i] + dist[i];
				k = i;
			}
		}
		cout << ma / 2 << endl;
		cout << x << " " << y << " " << k << endl;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值