luogu P3629 [APIO2010]巡逻

题面传送门
如果 k = 1 k=1 k=1显然非常简单,取树的直径即可。
考虑 k = 2 k=2 k=2怎么做。
第一条显然要取树的直径。
而第二条如果围成的环和第一条围成的环有重叠,那么重叠的边要走两次。所以我们可以把这几条重叠的边权值设为 − 1 -1 1,然后再跑一遍树的直径。
代码实现:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;
int n,m,k,x,y,z,maxn,maxs,dp[100039],ans,tot,pus,flag[100039],top[100039];
struct yyy{int to,w,z;};
struct ljb{
	int head,h[100039];
	yyy f[200039];
	inline void add(int x,int y,int z){
		f[head++]=(yyy){y,z,h[x]};
		h[x]=head-1;
	}
}s;
inline void dfs1(int x,int last,int d,int tops){
	top[x]=tops;
	if(d>maxn){
		maxn=d;
		maxs=x;
	}
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) dfs1(tmp.to,x,d+tmp.w,cur);
		cur=tmp.z;
	}
}
inline void dfs2(int x,int last){
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) {
			dfs2(tmp.to,x);
			maxn=max(maxn,dp[x]+dp[tmp.to]+tmp.w);
			dp[x]=max(dp[x],dp[tmp.to]+tmp.w);
		}
		cur=tmp.z;
	}
}
inline void dfs3(int x,int last,int d){
	if(d>maxn){
		maxn=d;
		maxs=x;
	}
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) dfs3(tmp.to,x,d+tmp.w);
		cur=tmp.z;
	}
}
int main(){
	register int i;
	memset(s.h,-1,sizeof(s.h));
	scanf("%d%d",&n,&k);
	ans=2*n-2;
	for(i=1;i<n;i++)scanf("%d%d",&x,&y),s.add(x,y,1),s.add(y,x,1);
	dfs1(1,0,0,-1);
	maxn=0;tot=maxs;
	dfs3(maxs,0,0);
	ans-=maxn-1;
	if(k==1){printf("%d\n",ans);return 0;}
	while(top[tot]!=-1)s.f[top[tot]].w*=-1,tot=s.f[top[tot]^1].to;
	while(top[maxs]!=-1)s.f[top[maxs]].w*=-1,maxs=s.f[top[maxs]^1].to;
	maxn=0;
	dfs2(1,0);
	printf("%d\n",ans-maxn+1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值