比赛 2025.12.13 评测结果 WWWWWAAWWWWWWWWWWWWWWWWWWWWWWW
题目名称 巡逻 最终得分 7
用户昵称 Yis 运行时间 0.321 s
代码语言 C++ 内存使用 4.37 MiB
提交时间 2025-12-13 12:29:24
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1000010;
int head[maxn],cnt=0,nxt[2*maxn],to[maxn*2],maxdeep[maxn],ans,cnted[maxn];
void addedge(int u,int v){
	to[++cnt]=u;
	nxt[cnt]=head[u];
	head[u]=cnt;
}
int dfs(int ind,int last){
	int ed=head[ind];
	int res=0;
	while(ed){
		if(to[ed]!=last){
			res=max(res,maxdeep[to[ed]]+1);
		}
		ed=nxt[ed];
	}
	maxdeep[ind]=res;
	return res;
}
int un1=0,un2=0;
int dfs2(int ind,int last){
	if(cnted[ind]<=2){
		int ed=head[ind];
		while(ed){
		if(to[ed]!=last){
			return dfs2(to[ed],ind);
		}
		ed=nxt[ed];
		}
		return 0;
	}else{
		int ma1=0,ma2=0;
		int ed=head[ind];
		while(ed){
		if(to[ed]!=last){
			int now=to[ed];
			if(maxdeep[now]>ma1){
				ma2=ma1;
				ma1=maxdeep[now];
				un1=now;un2=un1;
			}else if(maxdeep[now]>ma2){
				ma2=maxdeep[now];
				un2=now;
			}
		}
		ed=nxt[ed];
		}
		cnted[ind]-=2;
		return ma1+ma2;
	}
}
int dfs3(int ind,int last,int past){
	if(cnted[ind]<=2){
		int ed=head[ind];
		while(ed){
		if(to[ed]!=last){
			return dfs3(to[ed],ind,past+1);
		}
		ed=nxt[ed];
		}
		return past;
	}else{
		int ma1=0,ma2=0;
		int ed=head[ind];
		while(ed){
		if(to[ed]!=last&&to[ed]!=un1&&to[ed]!=un2){
			int now=to[ed];
			if(maxdeep[now]>ma1){
				ma2=ma1;
				ma1=maxdeep[now];
			}else if(maxdeep[now]>ma2){
				ma2=maxdeep[now];
			}
		}
		ed=nxt[ed];
		}
		return ma1+ma2;
	}
}
int main(){
	freopen("xunluo.in","r",stdin);
	freopen("xunluo.out","w",stdout);
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n,k;
	cin>>n>>k;
	cnted[1]=1;
	for(int i=0;i<n-1;i++){
		int u,v;
		cin>>u>>v;
		cnted[u]++;
		cnted[v]++;
		addedge(u,v);
		addedge(v,u);
	}
	dfs(1,0);
	ans=2*(n-1)+k;
	int t1=dfs2(1,0);
	if(t1==0){
		ans-=n-1;
	}else{
		ans-=t1;
		if(k==2){
			ans-=dfs3(1,0,0);
		}
	}
	cout<<ans<<endl;
	return 0;
}