AtCoder Grand Contest 001 C - Shorten Diameter

本文探讨了关于树的数据结构中直径与中心的概念,并通过算法实现了寻找树的中心点及边,进而解决特定问题。文章提供了完整的代码实现,包括DFS深度优先搜索的应用。

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

想到边上去了、但是没有推出一定存在题解说的两种情况


C.We use the following well-known fact about trees.
Let T be a tree, and let D be the diameter of the tree.


• If D is even, there exists an vertex v of T such that for each vertex w in
T, the distance between w and v is at most D/2.


• If D is odd, there exists an edge e of T such that for each vertex w in T,
the distance between w and one of the endpoints of e is at most (D −1)/2.
Here v and e are called centers of the tree.


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <bitset>

using namespace std;
#define LL long long
#define pb push_back
#define mk make_pair
#define pill pair<int, int>
#define fi first
#define se second
#define mst(a, b)	memset(a, b, sizeof a)
#define REP(i, x, n)	for(int i = x; i <= n; ++i)
const int MOD = 1e9 + 7;
const int qq = 2e3 + 10;
const LL INF = 1e9 + 10;
int n, k;
vector<int> G[qq];
int dis[qq][qq];
void Dfs(int rt, int u, int fa, int dep) {
	dis[rt][u] = dep;
	int sz = (int)G[u].size();
	for(int i = 0; i < sz; ++i) {
		int v = G[u][i];
		if(v == fa)	continue;
		Dfs(rt, v, u, dep + 1);
	}
}
pill pl[qq];

int main(){
	scanf("%d%d", &n, &k);
	for(int a, b, i = 1; i < n; ++i) {
		scanf("%d%d", &a, &b);
		G[a].pb(b), G[b].pb(a);
		pl[i] = mk(a, b);
	}
	for(int i = 1; i <= n; ++i) {
		Dfs(i, i, -1, 0);
	}
	int minx = n;
	for(int i = 1; i <= n; ++i) {
		int cnt = 0;
		for(int j = 1; j <= n; ++j) {
			if(dis[j][i] * 2 > k)	cnt++;
		}
		minx = min(minx, cnt);
	}
	for(int i = 1; i <= n - 1; ++i) {
		int cnt = 0;
		for(int j = 1; j <= n; ++j) {
			if(2 * min(dis[j][pl[i].fi], dis[j][pl[i].se]) + 1 > k)	cnt++;
		}
		minx = min(minx, cnt);
	}
	printf("%d\n", minx);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值