1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include<iostream> #include<cstring> #include<queue> using namespace std; typedef long long ll; typedef unsigned long long ull; template <typename T> inline void read(T&x){ int w = 0;x = 0; char ch = getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') w = 1; ch = getchar(); } while(ch>='0' && ch<='9'){ x = (x<<1)+(x<<3)+(ch^48); ch = getchar(); } if(w) x = ~x+1; } template <typename T,typename...Args> inline void read(T&t,Args&...args){ read(t);read(args...); } template <typename T> inline T Max(T x,T y){ return (x > y ? x : y); } const int N = 1e5+10; int n,m,cnt; struct{ int to,nex; }edge[N<<1]; int head[N],edge_num; inline void add(int x,int y){ edge[++edge_num].to = y; edge[edge_num].nex = head[x]; head[x] = edge_num; } int dis[N],fa[N],vis[N]; inline int bfs(int s,int flag){ memset(dis,0,sizeof(dis)); queue <int> q; q.push(s); int idx = 0; if(flag) fa[s] = 0; while(!q.empty()){ int now = q.front(); q.pop(); for(int i=head[now];i;i=edge[i].nex){ int tto = edge[i].to; if(dis[tto] || tto==s || vis[tto]) continue; if(flag) fa[tto] = now; dis[tto] = dis[now]+1; if(dis[tto]>dis[idx]) idx = tto; q.push(tto); } } return idx; } int main(){
read(n,m); for(int i=1,u,v;i<n;++i){ read(u,v); add(u,v); add(v,u); } int t1 = bfs(1,1),t2 = bfs(t1,1); if(m==1){ printf("%d",2*(n-1)-dis[t2]+1); return 0; } for(int i=t2;i;i=fa[i]) vis[i] = 1; int maxdis = dis[t2],maxn = 0; for(int i=t2,f,g,maxg=0;i;i=fa[i]){ vis[i] = 0; t1 = bfs(i,0);
++cnt; g = dis[t1]+cnt; f = dis[t1]-cnt; maxn = Max(maxn,f+maxg); maxg = Max(maxg,g);
t2 = bfs(t1,0); vis[i] = 1; maxn = Max(maxn,dis[t2]); } printf("%d",2*(n-1)-maxdis-maxn+2);
fclose(stdin); fclose(stdout); return 0; }
|