| 比赛 |
2025.12.13 |
评测结果 |
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
| 题目名称 |
巡逻 |
最终得分 |
100 |
| 用户昵称 |
梦那边的美好TT |
运行时间 |
0.895 s |
| 代码语言 |
C++ |
内存使用 |
4.89 MiB |
| 提交时间 |
2025-12-13 12:12:06 |
显示代码纯文本
#include<bits/stdc++.h>
#define N 100001
using namespace std;
int n,k,x,y,tot,lf=1,ans1,ans2,hd[N],nxt[N<<1],to[N<<1],ss[N<<1],fa[N],dep[N],v[N],d[N];
void add(int x,int y,int z){
to[++tot]=y;
nxt[tot]=hd[x];
ss[tot]=z;
hd[x]=tot;
return ;
}
void dfs(int x,int pre,int z,int t){
dep[x]=dep[pre]+z;
if(t==2) fa[x]=pre;
for(int i=hd[x];i;i=nxt[i]){
if(to[i]==pre) continue;
dfs(to[i],x,ss[i],t);
}
if(dep[x]>dep[lf]) lf=x;
return ;
}
void dp(int x,int pre){
for(int i=hd[x];i;i=nxt[i]){
if(to[i]==pre) continue;
if(v[x]&&v[to[i]]) ss[i]=-1;
dp(to[i],x);
ans2=max(ans2,d[x]+d[to[i]]+ss[i]);
d[x]=max(d[x],d[to[i]]+ss[i]);
}
return ;
}
int main(){
freopen("xunluo.in","r",stdin);
freopen("xunluo.out","w",stdout);
cin>>n>>k;
for(int i=1;i<n;i++){
cin>>x>>y;
add(x,y,1);
add(y,x,1);
}
dfs(1,0,0,1);
dfs(lf,0,0,2);
ans1=dep[lf];
if(k==1){
cout<<2*n-ans1-1<<endl;
return 0;
}
for(int i=lf;i;i=fa[i]) v[i]=1;
dp(1,0);
cout<<2*n-ans1-ans2<<endl;
return 0;
}