P3174 [HAOI2009] 毛毛虫

题意:给你一棵树,取出一根链和与链相邻的“脚”;问能取出的最大节点数是多少?

分析:很容易想到:f[u] 是 u 为当前子树根节点的毛毛虫头时子树内毛毛虫最大点数。但当时其实最大的疑问在于:如何选根节点 —— 假设选到了一个不在最终答案上的点座位根节点dfs,咋办?

   

 点4显然不会在最终的链上。当时到这里就想不下去了

但我们发现实际上维护每个当前点的【最大 + 次大】即可;不要忘了根节点,叶子节点的特判;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+15;
const int mo = 998244353;
#define pb push_back
#define pii pair<int,int>
#define ft first
#define sd second
#define ffor(i,a,b,c) for(int i=(a);i<(b);i+=(c))
#define For(i,a,b,c) for(int i=(a);i<=(b);i+=(c))
#define rfor(i,a,b,c) for(int i=(a);i>(b);i-=(c))
#define Rfor(i,a,b,c) for(int i=(a);i>=(b);i-=(c))
#define all(x) (x).begin(), (x).end()
#define debug1(x) cerr<<"! "<<x<<endl;
#define debug2(x,y) cerr<<"#  "<<x<<" "<<y<<endl;

void slv(){
	int n, m; cin >> n >> m;
	vector<vector<int>> E(n + 1);
	for (int i = 1; i < n; i++) {
		int u, v; cin >> u >> v;
		E[u].pb(v); E[v].pb(u);
	}
	vector<int> f(n + 1);
	int ans = 0;
	function<void(int, int)> dfs = [&] (int u, int fa) {
		int mx1 = 0, mx0 = 0;
		for (auto v : E[u]) {
			if (v == fa) continue;
			dfs(v, u);
			if (f[v] > mx1) {
				mx0 = mx1;
				mx1 = f[v];
			} else if (f[v] > mx0) {
				mx0 = f[v];
			}
		}
		int cnt = E[u].size() - (fa != 0);
		f[u] = mx1 + 1 + max(0, cnt - 1);
		ans = max(ans, mx1 + mx0 + 1 + max(0, cnt - 1 - (fa == 0)));
	};
	dfs(1, 0);
	cout << ans << '\n';
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	slv();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值