【codeforces 1029E - Tree with Small Distances】【树形dp+思维+贪心】【用最少的连1的边使得树上每个点到1的距离不超过2】

本文介绍了一种通过优化树状结构来确保所有节点与根节点距离不超过2的算法方案。通过对叶子节点及其父节点进行递归处理,实现最小化所需连接边数的目标。

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

【链接】:

https://codeforces.com/problemset/problem/1029/E

【题意】:

用最少的连1的边使得树上每个点到1的距离不超过2

【分析】:

离1最远的点需要连边的需求越大,从叶子节点考虑,肯定是父亲连边比叶子节点连边更优。父亲连边,改变父亲的父亲的距离,重复操作。在树形dp递归的过程中完成。

【代码】:

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
const int maxn = 200005;
vector<int>v[maxn];
int dis[maxn];
int ans = 0;

void dfs(int cur, int pre, int cnt) {
	dis[cur] = cnt;
	int flag = 0;
	for (int y : v[cur]) {
		if (y == pre)continue;
		dfs(y, cur, cnt + 1);
		if (dis[y] > 2) {
			flag = 1;
			dis[cur] = 1;
			dis[pre] = 2;
		}
	}
	if (flag)ans++;
}

int main() {
	int n;
	scanf("%d", &n);
	n--;
	while (n--) {
		int x, y;
		scanf("%d%d", &x, &y);
		v[x].push_back(y);
		v[y].push_back(x);
	}
	dfs(1, -1 ,0);
	printf("%d\n", ans);
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值