【CQOI2017】小Q的棋盘(贪心)

题意:给你一棵 n n n 个点的树,从根节点开始走 m m m 步,最多能遍历多少个节点。

题解:

考虑我们走的路径,设起点是 S S S,终点是 T T T,那么我们肯定是走的类似这么一条路径:

在这里插入图片描述

S → T S\to T ST 这条链的长为 l l l,那么我们在子树中走了 m − l m-l ml 步,子树中恰好会走 m − l 2 \frac{m-l}{2} 2ml 个点,那么我们总共会走 l + 1 + m − l 2 l+1+\frac{m-l}{2} l+1+2ml 个点。

那么我们挑 S → T S\to T ST 最长的那条链作为 l l l 肯定是最优的,即最长链。

#include<bits/stdc++.h>

#define N 110

using namespace std;

inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9')
	{
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		x=(x<<1)+(x<<3)+(ch^'0');
		ch=getchar();
	}
	return x*f;
}

int n,m;
int cnt,head[N],to[N<<1],nxt[N<<1];

void adde(int u,int v)
{
	to[++cnt]=v;
	nxt[cnt]=head[u];
	head[u]=cnt;
}

int dfs(int u,int fa)
{
	int maxn=0;
	for(int i=head[u];i;i=nxt[i])
	{
		int v=to[i];
		if(v==fa) continue;
		maxn=max(maxn,dfs(v,u)+1);
	}
	return maxn;
}

int main()
{
	n=read(),m=read();
	for(int i=1;i<n;i++)
	{
		int u=read()+1,v=read()+1;
		adde(u,v),adde(v,u);
	}
	int l=dfs(1,0);
	if(m<=l) printf("%d\n",m+1);
	else printf("%d\n",min(n,l+1+(m-l)/2));
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值