【集训DAY15】Boring【树形DP】

96 篇文章 0 订阅
21 篇文章 0 订阅

在这里插入图片描述

思路:

直接从最大的儿子跳到次大的儿子就完成了转移

c o d e code code

#include<iostream>
#include<cstdio>

using namespace std;

const int MAXN = 1e6 + 10;

int n, m, ru[MAXN], maxx[MAXN], f[MAXN];
int head[MAXN], tot, ans;

struct node {
	int to, next;
}b[MAXN * 2];

void add(int x, int y) {
	b[++ tot] = (node) { y, head[x] };
	head[x] = tot;
}

void dfs(int x, int fa) {
	int d = 0;
	for(int i = head[x]; i; i = b[i].next) {
		int y = b[i].to;
		if(y == fa) continue;
		d ++;
		dfs(y, x);
	}
	if(d == 0) { f[x] = 1; maxx[x] = 1; }
	if(d == 1) {
		for(int i = head[x]; i; i = b[i].next) {
			int y = b[i].to;
			if(y == fa) continue;
			maxx[x] = maxx[y] + 1;
			f[x] = maxx[x];
		}
	}
	if(d >= 2) {
		int M = 0, CM = 0;
		for(int i = head[x]; i; i = b[i].next) {
			int y = b[i].to;
			if(y == fa) continue;
			if(maxx[y] > M) CM = M, M = maxx[y];
			else if(maxx[y] == M) CM = M;
			else if(maxx[y] > CM) CM = maxx[y]; 
		}
		maxx[x] = M + d;
		f[x] = CM + M + d - 1;
	}
	if(fa != 0)
		ans = max(ans, max(maxx[x], f[x] + 1));
	else ans = max(ans, max(maxx[x], f[x]));
}

int main() {
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; i ++) {
		int x, y;
		scanf("%d%d", &x, &y);
		add(x, y), add(y, x), ru[x] ++, ru[y] ++;
	}
	dfs(1, 0);
	printf("%d", ans);
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值