Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K.
You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.
You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected.
Find the minimum number of vertices that you need to remove in order to produce a good tree.
Constraints
2≦N≦2000
1≦K≦N-1
1≦A_i≦N, 1≦B_i≦N
The graph defined by A_i and B_i is a tree.
Input
The input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}
Output
Print the minimum number of vertices that you need to remove in order to produce a good tree.
Examples
Input
6 2
1 2
3 2
4 2
1 6
5 6
Output
2
Input
6 5
1 2
3 2
4 2
1 6
5 6
Output
0
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to understand the problem. We have an undirected tree with N vertices. We can remove any set of vertices (and all incident edges). The resulting graph (the induced subgraph on the remaining vertices) must be connected and must be a tree? Actually after removal, we get a graph on remaining vertices that is a tree? The original is a tree; removing vertices yields a forest, but they require it to be connected, so the remaining vertices must induce a connected subgraph, which will be a tree because it's a subgraph of a tree (no cycles) and connected => tree. So we need to keep a connected subset of vertices that forms a tree with diameter <= K. We want to minimize the number of vertices removed, i.e., maximize the number of vertices kept, but subject to the condition that the kept vertices induce a connected subtree with diameter <= K.
But careful: when we remove vertices, we don't have to keep the induced subgraph on kept vertices? Actually "remove zero or more vertices from the tree, so that the resulting tree is good." The resulting tree is the graph that remains after removal; we consider it as a tree (it must be connected). So we are selecting a set of vertices to keep, such that the induced subgraph on that set is connected and has diameter <= K. The objective: minimize number removed = N - |kept|.
Thus we want to maximize |kept|.
We need to compute the maximum size of a connected induced subtree with diameter <= K.
Given constraints N <= 2000, we can afford O(N^2) or O(N^2 log N) solutions.
This problem is known as "largest subtree of a tree with bounded diameter" or "find largest connected subgraph of tree with diameter <= K".
Observation: For any tree, the diameter is determined by the two farthest nodes. If we have a connected induced subtree (i.e., a connected subset of nodes forming a tree), it's essentially a tree that is a subgraph of the original tree; it must be a connected set of nodes that is also "induced" in the sense that if we keep two nodes, we must keep all nodes on the path between them? Actually, when we keep a set of vertices S, the resulting graph is the induced subgraph on S, i.e., we keep edges whose both endpoints are in S. Since original graph is a tree, the induced subgraph on S might not be connected even if S contains all nodes on paths? Actually, for any set S, the induced subgraph is just the edges between nodes in S. If S is a set of vertices, and we consider the induced subgraph, it will be a forest. For it to be a tree (connected), S must be such that for any two nodes in S, the entire path between them in the original tree is also in S? Not necessarily. In a tree, the induced subgraph on S is connected iff S contains all vertices on the paths between any two vertices in S? Let's check: In a tree, edges are only those connecting nodes that are directly adjacent. For S to induce a connected subgraph, we need that for any two nodes u,v in S, there is a path from u to v using only vertices in S. Since original tree has a unique simple path between u and v, if that path includes any vertex not in S, then the induced subgraph cannot contain that missing vertex, so the path is broken. So the induced subgraph is connected if and only if S is "convex" in the tree sense: for any u,v in S, all vertices on the unique path between u and v also belong to S. In other words, S must be a subtree (connected subgraph) that is also an induced subgraph. In trees, the notion of connected induced subgraph is equivalent to a set that is connected in the original tree and includes all intermediate nodes. But careful: if S is a connected set of nodes in the tree, does it automatically contain all nodes on paths between them? Actually, connectivity in the induced subgraph means that for each pair, there is a path within S using edges of the original tree that are present only when both endpoints are in S. But if S is connected as a set in the original tree (i.e., the subgraph induced by S is connected), then for any u,v in S, there exists a path u = x0, x1, ..., xm = v where each edge (xi, xi+1) is an edge in the original tree and each xi ∈ S. Since the tree has unique simple paths, this path must be the unique path. Thus the unique simple path between u and v is included in S (all vertices on it). So indeed S must be "path-closed". So the kept set S must be a connected induced subtree (i.e., a subtree) of the original tree. It's essentially any connected subset of nodes that is closed under taking paths: it's a subtree.
Thus we need to select a subtree (connected induced subgraph) of the original tree of maximum size with diameter ≤ K.
Now N=2000. We can consider a DP.
Think about the diameter constraint: diameter ≤ K means that the longest distance between any two vertices in the induced subtree is ≤ K.
We can reinterpret: The subtree's "radius" or we can root the tree at some center. For a tree with diameter ≤ K, there exists a center (possibly an edge or vertex) such that all vertices are within distance ≤ floor(K/2) from the center? Actually, for a tree, the diameter ≤ K if and only if there exists a vertex (or edge) such that every vertex is at distance ≤ ⌊K/2⌋ from that vertex (if K even, center vertex; if K odd, center edge and distance ≤ (K-1)/2 from each endpoint?). More precisely: For any tree T, let the set of centers be defined as: if diameter d is even, there is a unique central vertex such that max distance from it is d/2; if d odd, there are two central vertices (adjacent) with max distance (d+1)/2? Actually, the radius r = ceil(d/2). The minimum eccentricity is r. For a given tree, there is at least one vertex with eccentricity ≤ r. For the condition diameter ≤ K, we can say that there exists a vertex v such that the maximum distance from v to any other vertex in the subtree ≤ floor(K/2)? Check: If diameter ≤ K, then the eccentricity of any vertex is at most K, but we want to find a vertex whose distance to all others ≤ ceil(K/2) maybe? Actually consider a path of length K (K edges). Its diameter = K. The central vertex (if K even) has max distance K/2. The central edge (if K odd) has each endpoint at distance (K+1)/2 from the farthest endpoint? Wait: path with K edges, number vertices = K+1. For K even: say edges = 2m, then diameter = 2m. The central vertex is at position m from both ends, so max distance from that central vertex is m = K/2. For K odd: edges = 2m+1, diameter = 2m+1. There is no single vertex that is within m of both ends; the central edge connects two vertices each at distance m+1 from one end? Actually, pick the middle vertex? For path with vertices 0,1,...,2m+1 (edges 2m+1). The middle vertex is m+1 (if we count 0-based). Its distance to vertex 0 is m+1, to vertex 2m+1 is m. So max is m+1 = ceil(K/2) (since K=2m+1, ceil(K/2)=m+1). So the minimal maximum distance (radius) is ceil(K/2). So condition diameter ≤ K is equivalent to existence of a vertex v such that all vertices are within distance ≤ ceil(K/2) from v? Actually if we can find a vertex v such that max distance from v ≤ r, then diameter ≤ 2r. Conversely, if diameter ≤ K, then the radius ≤ ceil(K/2). So there exists a vertex v with eccentricity ≤ ceil(K/2). So the condition can be expressed as: The subtree must be contained in a ball of radius floor(K/2) around some vertex if K is even? Wait: if K is even, K=2r, then radius r implies diameter ≤ 2r. If K is odd, K=2r+1, then radius r+1? Actually for diameter ≤ 2r+1, radius ≤ r+1? Since ceil((2r+1)/2)=r+1. So there exists a vertex v such that all vertices within distance ≤ r+1 from v. But we want to guarantee diameter ≤ K. So for any subtree, if there exists a vertex v with max distance ≤ L, then diameter ≤ 2L. So if we want diameter ≤ K, we can set L = floor(K/2) to get diameter ≤ 2floor(K/2) which could be less than or equal K? For K odd, 2floor(K/2) = 2r which is less than 2r+1; so it's stricter. So using L = floor(K/2) would ensure diameter ≤ 2L ≤ K, but may not capture all trees with diameter ≤ K when K odd? Actually if K is odd, a tree can have diameter = 2r+1 and still satisfy ≤ K. For such a tree, the minimal max distance from a vertex is r+1. So we cannot guarantee existence of a vertex with max distance ≤ floor(K/2) = r; but we can guarantee existence of an edge such that each vertex is within distance r+1 of one of its endpoints? Possibly the subtree can be covered by two overlapping balls of radius r+1 around two adjacent vertices? More precisely, if we have a center edge (u,v), then every node is within distance ≤ r+1 from u or v. And the diameter = distance between farthest nodes ≤ (distance from farthest to u) + (distance from farthest to v)??? Not exactly. But for a tree with diameter ≤ 2r+1, there exists an edge (the central edge) such that all vertices are within distance r from either u or v? Let's check path length 2r+1: vertices 0 to 2r+1. Central edge between r and r+1. The farthest vertex from u=r is vertex 2r+1 at distance r+1, and from v=r+1 is vertex 0 at distance r+1. But within distance r from u, we have vertices r-r to r+r? Actually distance r from u: vertices from 0? r - r = 0? Actually u=r, distance to 0 is r, so yes vertex 0 is at distance r, vertex 2r+1 is at distance r+1. So not all vertices are within distance r from either endpoint? Vertex 2r+1 is distance r+1 from u, but distance r from v? v=r+1 to 2r+1 is r, yes! So for any vertex on the path, it is within distance ≤ r from either u or v. Indeed because the path is divided: vertices 0...r are within distance ≤ r from u (since u=r), vertices r+1...2r+1 are within distance ≤ r from v (since v=r+1). So all vertices are within distance ≤ r from one of the two centers. So condition: There exists an edge (u,v) such that every vertex in the subtree has distance ≤ r from u or from v, where r = floor(K/2)? Let's check: If K=2r (even), we can just use a single vertex center: all vertices within distance ≤ r. If K=2r+1 (odd), we can use two adjacent vertices such that each vertex is within distance ≤ r from one of them. In both cases, the maximum distance between any two vertices is at most (distance from one to u + distance from other to v + 1) maybe? Let's derive: If each node is either within distance r of u or within distance r of v, then consider any two nodes x,y. If both near u, distance(x,y) ≤ 2r ≤ 2r+1 = K. If both near v, ≤ 2r ≤ K. If x near u, y near v, then distance(x,y) ≤ distance(x,u)+1+distance(v,y) ≤ r+1+r = 2r+1 = K. So indeed diameter ≤ 2r+1 = K. So condition works.
Thus we have two characterizations: For even K, the subtree is contained in a ball of radius K/2 around some vertex. For odd K, the subtree is contained in the union of two balls of radius floor(K/2) around two adjacent vertices, i.e., for some edge, each node is within distance floor(K/2) of one of its endpoints.
Alternatively, we can approach by enumerating the "center" (vertex or edge) and then consider the maximal subtree within the distance constraint that remains connected? But if we take all vertices within a certain distance from a center, the induced subgraph might not be connected? Actually, in a tree, the set of all vertices within distance D from a given vertex v is connected? Not necessarily if the tree has branches? Wait, consider a tree and take all nodes within distance <= D from v. That set includes v and all nodes whose shortest path to v ≤ D. This set is connected? In a tree, the set of nodes at distance <= D from v is indeed connected because for any node x in the set, the unique path from v to x lies entirely within the set (since all intermediate nodes have distance <= distance(x) <= D). So it's connected. Similarly, if we take union of two balls around adjacent vertices u and v, each ball individually is connected; but the union of two connected sets that intersect (the edge between u and v ensures intersection) is connected. And all nodes in the union are those within distance D from u or v. This union is also connected. So these candidate sets are valid subtrees.
Thus, for any center (vertex or edge) and radius r = floor(K/2), the set of vertices within distance ≤ r from the center (vertex case) or from either endpoint of the center edge (edge case) forms a subtree with diameter ≤ K. However, note that for odd K, we may get a larger subtree by not necessarily taking all vertices within distance r from u or v; perhaps some vertices that are beyond distance r from both but still the overall diameter ≤ K? Let's check: If we have an edge center (u,v) with r = floor(K/2) (so K=2r+1). Suppose there is a vertex w such that distance(w, u) = r+1 and distance(w, v) = r+2? That can't happen because u and v are adjacent, so distances differ by at most 1. Actually, for any vertex w, dist(w,u) and dist(w,v) differ by exactly 1, because the unique path from w to u vs v goes through either u or v; if w is closer to u, then dist(w,v)=dist(w,u)+1. So if dist(w,u) > r, then dist(w,u) >= r+1, so dist(w,v) >= r (if r+1? Actually if dist(w,u)=r+1, then dist(w,v) is either r or r+2? Since they differ by 1, if w is on the side of u, then dist(w,v)=dist(w,u)+1 = r+2; if w is on the side of v, then dist(w,u)=dist(w,v)+1; but if dist(w,u) > r and dist(w,v) > r? Let's see: The maximum allowed for diameter ≤ K=2r+1 is that for any two vertices x,y, distance(x,y) ≤ 2r+1. If we have a vertex w with dist(w,u)=r+1 and w is on u's side, then dist(w,v)=r+2. Then consider w and some vertex z that is at distance r+1 from v (on v's side) might have distance (r+2)+(r+1)+1? Actually careful: In a tree, if we have central edge (u,v), the two sides are the components when removing edge (u,v). The subtree we keep must be connected and we can choose any set of vertices, but to keep diameter ≤ 2r+1, we cannot include vertices that are too far from the center. The condition that each vertex is within distance r of u or v is necessary? Let's test: Suppose we take a vertex w such that dist(w,u) = r+1 and dist(w,v) = r+2 (so w is on u's side beyond r+1). Consider also a vertex z such that dist(z,v) = r+1 and dist(z,u) = r+2 (on v's side). Then distance(w,z) = dist(w,u) + 1 + dist(v,z) = (r+1)+1+(r+1)=2r+3 > 2r+1. So diameter would exceed K. So we cannot have vertices both at distance r+1 from the respective far side? Actually if we have any vertex w with dist(w,u) > r+1? That would be worse. But could we have only vertices on one side beyond r? Suppose we have w with dist(w,u)=r+1, and no vertex on v's side beyond r. Then the farthest pair might be w and some vertex on u's side? For w and another vertex x on u's side, distance ≤? The maximum distance between two vertices on the same side is bounded by 2r+2? Let's compute: On side of u, the distances from u to farthest node could be r+1. Then two nodes on that side could have distance up to 2(r+1) = 2r+2 > 2r+1. So even if only one side goes beyond r, the diameter can exceed K because two nodes on that side could both be at distance r+1 from u but on opposite branches? Actually consider the u side: the set of nodes at distance <= r+1 from u; the diameter of that set could be up to 2(r+1) if there are two nodes at distance r+1 in different branches. For example, a star: u is center, with leaves at distance 1. But that's not a path. More specifically, in a tree, if all nodes are within distance D from u, the diameter could be up to 2D (two leaves at distance D from u). So if we allow nodes at distance r+1 from u, then the diameter could be up to 2(r+1) = 2r+2 > 2r+1. However, is it possible to have a set with diameter ≤ 2r+1 that includes some nodes at distance r+1 from u? Possibly if we restrict that there is at most one branch extending to depth r+1, or that the set is such that the farthest nodes are not both at distance r+1 from u? For instance, if we have a path of length 2r+1, the central edge is (u,v). The node at one endpoint is at distance r+1 from u (and r from v). The other endpoint is at distance r+1 from v (and r from u). So there exist nodes at distance r+1 from u. But note that in that path, any node at distance r+1 from u is exactly the leaf on u's side, and any node on v's side is at distance ≤ r from v (or r+1 from u?). So in that case, the node at distance r+1 from u is only one leaf, not two; the diameter is 2r+1. So having a node at distance r+1 from u is allowed as long as we don't have two nodes at distance r+1 from u that are in different branches? Actually, if we have two nodes at distance r+1 from u, each being leaf in different branches, then the distance between them is at least (r+1)+(r+1)=2r+2 > 2r+1, so diameter exceeds K. So the condition that each node is within distance r of u or v is sufficient but not necessary? Let's see: Suppose we have a set where all nodes are within distance r of u, except one leaf that is at distance r+1 from u but also within distance r of v? Wait if it's at distance r+1 from u, then to be within distance r of v, we need dist(w,v) ≤ r. But dist(w,u) and dist(w,v) differ by 1, so if dist(w,u)=r+1, then dist(w,v) is either r or r+2. It cannot be r because then dist(w,u)=dist(w,v)+1 = r+1, so dist(w,v)=r. That would be possible only if w is on the side of v? Actually, if w is on the side of v, then the path from w to u goes through v, so dist(w,u) = dist(w,v)+1. So if dist(w,u)=r+1, then dist(w,v)=r. That means w is within distance r of v, and also at distance r+1 from u. So that node satisfies being within distance r of v. So in the edge-center characterization, the condition "each vertex is within distance r of u or v" would include w because it's within r of v. So indeed that condition includes vertices at distance r+1 from u only if they are within r of v. In the path example, the leaf on u's side: dist to u = r+1, dist to v = r+2? Actually for the leaf on u's side (the endpoint opposite v), dist to u = r+1? Let's be concrete: K=5 => r=2 (floor(5/2)=2). Path of length 5 (6 nodes): nodes: a0 - a1 - a2 - a3 - a4 - a5. Choose central edge between a2 and a3 (since 5 edges, central edge). Then r=2. For leaf a0: dist(a0, a2)=2, dist(a0, a3)=3. So it is within distance 2 of a2, so it's within r of u (a2). For leaf a5: dist(a5, a3)=2, dist(a5, a2)=3. So within r of v (a3). So indeed all nodes are within distance r of either endpoint? a0 is within 2 of a2, a5 within 2 of a3, a1 within 1 of a2, a2 within 0 of a2, a3 within 0 of a3, a4 within 1 of a3. So yes, condition holds. But a node at distance r+1 from u and not within r of v would be dist(w,u)=r+1, dist(w,v)=r+2. That node would be on u's side but beyond r+1? Actually r+1 > r, so not within r of u, and r+2 > r, so not within r of v. That node would violate condition. Could such a node be included in a subtree of diameter ≤ 2r+1? Possibly if the subtree does not include any node far from u on the other side? Let's test: Suppose we have a tree that is a path: u - x - ... - w, where w is at distance r+2 from u. If we include w and also include u, the distance between w and u is r+2, which > r+1? Wait diameter bound is 2r+1. If r+2 ≤ 2r+1? For r≥1, r+2 ≤ 2r+1 is true for r≥1? For r=2, 2r+1=5, r+2=4 ≤5. So just having w at distance 4 from u is okay as long as the farthest pair is not >5. However, the diameter would be at most the maximum distance between any two nodes. If we only include nodes from u to w (a path segment), the diameter equals distance between u and w = r+2, which is ≤2r+1. So that seems allowed. But does it satisfy the condition? For r=2, we have nodes at distances 0,1,2,3,4 from u. That's 5 nodes? Actually distance 4 yields 5 nodes? Path length 4 edges: u - a - b - c - w (distance 4). That subtree has diameter 4 (if K=5, that's fine). The edge-center condition with r=2: is there an edge (or vertex) such that every node is within distance 2 of one of two adjacent vertices? Let's test: Could we choose an edge? Suppose we take edge (b,c) maybe? Let's find: distance from u to b? u->a->b distance 2, so u within 2 of b. w to c? w to c distance 1? Actually w to c: w is c's neighbor? Path: b - c - w? Actually if we have nodes: u - a - b - c - w. So edges: u-a, a-b, b-c, c-w. Choose edge (b,c). Then distances: u to b =2 ≤2, u to c =3 >2; but u is within 2 of b, okay. a to b=1 ≤2, a to c=2 ≤2. b itself obviously. c itself. w to c=1 ≤2, w to b=2 ≤2. So all nodes are within distance 2 of either b or c. Indeed u distance 2 from b, w distance 1 from c. So condition holds. So even though w is at distance 4 from u, it is within distance 2 of c. So the condition still holds. So maybe the condition "there exists an edge (u,v) such that all vertices are within distance r of u or v" is necessary for diameter ≤ 2r+1? Let's attempt to prove: Given a tree T with diameter ≤ 2r+1, consider its center(s). If diameter is exactly 2r+1, then there is a central edge (maybe not unique). If diameter is less, say ≤ 2r, then there is a central vertex with eccentricity ≤ r, which also satisfies the edge condition? Possibly not, but we can always represent as edge condition by taking any edge incident to central vertex? For diameter ≤ 2r, there exists a vertex c with eccentricity ≤ r. Then for any vertex x, dist(x,c) ≤ r. Pick any neighbor v of c. Then dist(x,c) ≤ r, and if dist(x,c) ≤ r, then x is within r of c (or maybe also within r of v if it's on the other side). But is it guaranteed that x is within r of c or v? Since c is one of the endpoints, x within r of c works. So the condition holds with edge (c,v) because every vertex is within r of c (so within r of c) or could also be within r of v? So it holds. So the edge condition is sufficient and also necessary? I think for any tree with diameter ≤ 2r+1, there exists an edge (u,v) such that all vertices are within distance r of u or v. This is a known property: the tree's center is either a vertex (if diameter even) or an edge (if diameter odd). In the even case, diameter = 2r, we can pick any edge incident to the center? Actually, if diameter = 2r, the center vertex c has eccentricity r. Then for any vertex x, dist(x,c) ≤ r. So x is within distance r of c. But to satisfy the edge condition, we need to pick an edge (c, v) (some neighbor v). Then for any x, if dist(x,c) ≤ r, then x is within r of c, so condition satisfied. So yes, the edge condition holds. If diameter = 2r+1, the central edge (u,v) has the property that every vertex is within distance r+1 of u and v? Actually, the property is that every vertex is within distance r+1 of both? Wait typical definition: For a tree with diameter odd = 2r+1, there is a central edge (u,v) such that the maximum distance from u to any vertex is r+1 and from v is r+1. But the condition we want is within distance r of u or v. Since r < r+1, not all vertices are within distance r of u or v; some may be at distance r+1 from both? Let's examine: In a tree with diameter 2r+1, take the central edge (u,v). Then the farthest vertex from u is at distance r+1, and similarly for v. Could there be a vertex at distance r+1 from both u and v? If a vertex w is at distance r+1 from u, then its distance from v is either r or r+2. Since they differ by 1, it's either r or r+2. If it were r, then dist(w,u)=r+1, dist(w,v)=r => w is within r of v. If it were r+2, then dist(w,u)=r+1? Actually if dist(w,u)=r+1, then dist(w,v) could be r (if w is on v's side) or r+2 (if w is on u's side). But can it be r+2? If w is on u's side such that path from w to v goes through u, then dist(w,v)=dist(w,u)+1 = r+2. So w would be at distance r+2 from v, not within r of v. But would such a vertex exist? For diameter = 2r+1, the maximum distance from u is r+1. So there cannot be a vertex at distance r+2 from v? Wait, v's maximum distance is also r+1. So if w is at distance r+2 from v, that would exceed r+1, contradiction. Therefore, there is no vertex with dist(w,u)=r+1 and dist(w,v)=r+2. Because that would mean dist(w,v)=r+2 > r+1, contradicting that the eccentricity of v is r+1. So indeed, any vertex at distance r+1 from u must be at distance r from v. Similarly, any vertex at distance r+1 from v must be at distance r from u. Thus every vertex is within distance r of either u or v. So the condition holds. So indeed, for any tree with diameter ≤ 2r+1, there exists an edge (u,v) such that all vertices are within distance r of u or v.
Thus, the set of all vertices that can be included in a subtree with diameter ≤ K corresponds exactly to those sets that are subsets of some "ball union" around an edge (or vertex for even K) of radius r = floor(K/2). But note: taking the whole ball union around an edge yields a subtree that is connected and with diameter ≤ K, but maybe we can include some vertices outside these balls and still have diameter ≤ K? Let's test with an example: Suppose K=3 (odd, r=1). We want diameter ≤ 3. Consider a tree that is a star with center c and leaves at distance 1. If we take the whole star, diameter is 2 (≤3). Now consider the edge condition with r=1: For any edge, say between c and leaf L, the union of balls radius 1 around c and L includes all vertices? ball radius 1 around c includes all leaves (distance 1) and c; ball around L includes L and its neighbors: only c and maybe? L's neighbors only c. So union includes all vertices. So it's fine.
What about a more complex tree: Suppose we have a path of length 4 (5 nodes) and K=3 (r=1). The path: 1-2-3-4-5. Diameter of whole path is 4 >3, so not allowed. Can we include all nodes except maybe one? The maximum subtree with diameter ≤3? Possibly nodes 1-2-3-4 (diameter 3) or 2-3-4-5 (diameter 3). So the maximum size is 4. The edge condition: r=1. Consider edge (2,3): ball radius 1 around 2 includes {1,2,3}; around 3 includes {2,3,4}. Union = {1,2,3,4} size 4. That's optimal. For edge (3,4): union = {2,3,4,5} also size 4. So indeed the optimal is captured.
But could there be a subtree with diameter ≤K that is not fully contained in any such union? Suppose we have a tree that is not a path but has branches. For K=2 (even, r=1). Condition: there exists a vertex c such that all vertices are within distance 1 from c. That is exactly that the subtree has diameter ≤2. This means the subtree is a star centered at c (maybe with some edges among leaves? but in a tree, leaves are not connected to each other). So it's a set of vertices all adjacent to c, plus c itself. So indeed, any such subtree is exactly the closed neighborhood of c: all vertices that are either c or its neighbors. But note: we could also have a subtree that is just a single edge (two vertices) which is also diameter 1 ≤2, but that is also a star with center at one of them? Yes, if we take vertices {u,v} with edge, then they are both within distance 1 from u (or v). So it's contained in ball of radius 1 around u. So again.
Thus, it seems that the maximum size subtree with diameter ≤ K is achieved by taking for some center (vertex for even K, edge for odd K) the set of all vertices whose distance to the center(s) ≤ r (with r = floor(K/2)), i.e., the "closed ball" around a vertex for even K, and the union of two closed balls of radius r around the endpoints of an edge for odd K. However, is it always maximal? Could there be a subtree that includes vertices beyond distance r from both endpoints of the best edge but still has diameter ≤ K? Let's try to construct a counterexample.
Suppose K=3 (r=1). Consider a tree shaped like a "Y": a central node c with three branches: branch1: c - a - a1; branch2: c - b; branch3: c - d. So vertices: c, a, a1, b, d. Distances: a1 to b: a1-a-c-b = 3 edges => distance 3. So the whole tree has diameter 3? a1 to b distance 3, that's exactly K=3. So whole tree (size 5) has diameter 3, which is allowed. Does it satisfy the edge condition with r=1? Need an edge (u,v) such that every vertex is within distance 1 of u or v. Let's see if such an edge exists. Try edge (c,a): ball radius1 around c = {c, a, b, d} (since c's neighbors: a,b,d); ball around a = {a, c, a1}. Union = {c, a, b, d, a1} = all vertices. Yes, it works. So it's contained.
Now consider a tree where diameter is exactly K but the central edge is not obvious? Actually the property we proved earlier shows that any tree with diameter ≤ 2r+1 has such an edge. So it's a necessary condition. That is, if a tree T has diameter ≤ 2r+1, then there exists an edge (u,v) such that every vertex is within distance r of u or v. So T is a subset of the union of balls of radius r around u and v. However, if T is a subtree (i.e., induced connected subset) with diameter ≤ K, then it is itself a tree with diameter ≤ K, so it must satisfy that condition. Therefore T is contained in the union of balls of radius r around some edge (or around a vertex for even K). But that union is defined in the original tree, not in T. However, the set of vertices in that union might include vertices that are not in T, but T is a subset. So the maximal possible T for a given center is exactly the union of balls (since that set itself is a valid tree with diameter ≤ K). But wait, is the union of balls always itself a tree with diameter ≤ K? We argued yes: for an edge (u,v) with r = floor(K/2) (odd K), the set S = { w | dist(w,u) ≤ r or dist(w,v) ≤ r } is connected and its diameter ≤ 2r+1 = K. So S is a valid subtree. So the maximum size achievable is at least the size of the largest such S (over all choices of centers). Could there be a subtree larger than any such S? Suppose we take a center vertex for even K, S = ball of radius K/2 around v. That's a valid subtree. Could we get a larger subtree that still has diameter ≤ K but not contained in any such ball? That would be a tree with diameter ≤ K but larger than any ball of radius K/2 around a vertex? For even K, any tree with diameter ≤ K must have a center vertex c with eccentricity ≤ K/2. So all vertices are within distance ≤ K/2 from c. Thus the entire tree is contained in the ball of radius K/2 around c. So the tree itself is a subset of that ball. Therefore the size of the tree cannot exceed the size of that ball (which is exactly the number of vertices within distance ≤ K/2 from c). But the ball of radius K/2 around c may include vertices not in the tree; but if we consider the maximal possible tree, it could be exactly that ball. However, could the ball be larger than the tree? The ball is defined based on distances in the original tree. The original tree has many vertices. If we take S = ball of radius K/2 around c, that includes all vertices within that distance in the original tree. That S might have diameter ≤ K? Yes. So it's a candidate. Therefore the maximum size of a subtree with diameter ≤ K is at least max over centers of |ball| (or union of balls). But is it possible that there is a subtree T with diameter ≤ K that is not entirely contained in any such ball? As argued, for even K, any such T has a center c such that every vertex in T is within distance ≤ K/2 from c (the center of T). However, that center c is a vertex in T, but the ball of radius K/2 around c in the original tree includes all vertices of T, but also may include others. So T is a subset of that ball. So |T| ≤ |ball around c|. So the maximum possible |T| is at most the maximum over vertices of the size of ball of radius K/2. And since that ball itself is a valid subtree, the maximum equals the maximum ball size. So for even K, the answer is N - max_{v} |B(v, K/2)|, where B(v, r) = set of vertices within distance ≤ r from v.
For odd K, we have a similar situation: any tree T with diameter ≤ 2r+1 has a central edge (u,v) such that all vertices are within distance r of u or v. In the original tree, the union of balls of radius r around u and v, call S(u,v) = { w | dist(w,u) ≤ r or dist(w,v) ≤ r }, contains T. But is S(u,v) necessarily a valid subtree? Yes, as argued. So |T| ≤ |S(u,v)|. And S(u,v) is a candidate. So the maximum possible |T| is at most max over edges of |S(u,v)|. And since S(u,v) itself is valid, the maximum equals that maximum. Therefore the answer is N - max_{center} |S_center|, where center is a vertex if K even (ball radius K/2) or an edge if K odd (union of balls radius floor(K/2) around endpoints).
Thus the problem reduces to: Given a tree of up to 2000 vertices, compute the maximum number of vertices that can be kept, which is the maximum size of a "ball" of radius R (R=K/2 for even K) centered at a vertex, OR the maximum size of the union of two balls of radius R centered at the endpoints of an edge (with R = floor(K/2) for odd K). Then answer = N - max_kept.
But careful: For even K, R = K/2 is integer. For odd K, R = (K-1)/2 integer.
Now is there any nuance? The union of two balls of radius R around u and v (adjacent) is exactly the set of vertices whose distance to {u,v} is ≤ R. But note that these balls overlap; we should count vertices only once. So we need to compute for each edge (u,v): |B(u,R) ∪ B(v,R)|. Similarly for vertices: |B(v,R)|.
Thus we can precompute distances between all pairs? N=2000, we can compute all-pairs distances via BFS from each node (O(N^2)) or using simple DP given tree, but O(N^2) is fine (2000^2=4e6). Then for each vertex v, we can count how many nodes have distance <= R from v (by checking distance array). Similarly for each edge (u,v), we count nodes with min(dist to u, dist to v) <= R.
So a straightforward solution: Compute distance matrix dist[u][v] using BFS from each node (since tree, BFS from each node O(N*(N+E)) = O(N^2) because each BFS is O(N) (tree edges N-1). Actually BFS from each node in a tree: for each source, run DFS/BFS to compute distances to all nodes: O(N) per source, total O(N^2). That's fine.
Then for each vertex v, count number of nodes with dist[v][w] <= R_even? But careful: For even K we use R = K/2; for odd we use R = floor(K/2). So we compute two sets maybe.
Implementation: read N,K. Build adjacency list. If K is even: R = K//2. Compute max_kept = max over v of count of nodes with distance <= R from v. If K is odd: R = K//2 (integer division truncates, e.g., K=5 => R=2). For each edge (u,v), count nodes where min(dist[u][w], dist[v][w]) <= R. Keep max over edges. Answer = N - max_kept.
But is there any case where the optimal subtree is not exactly a ball/union of balls? Let's double-check the necessity argument. For even K, we used the property that any tree T with diameter ≤ 2R (since K even, K=2R) has a center vertex c such that all vertices are within distance ≤ R from c. This is a known fact: The center of a tree is the set of vertices with minimum eccentricity. If diameter ≤ 2R, then the eccentricity of any vertex is at most 2R, but the minimum eccentricity (radius) is at most R? Actually radius = ceil(diameter/2). If diameter ≤ 2R, then radius ≤ R. So there exists a vertex c with eccentricity ≤ R. So indeed all vertices in T are within distance ≤ R from c. So T ⊆ B_T(c,R), but B_T(c,R) is the set of vertices in T within distance ≤ R from c (within T). However, the ball in the original tree B_original(c,R) includes also vertices not in T but within distance ≤ R from c in the original tree. So T is a subset of B_original(c,R). So |T| ≤ |B_original(c,R)|. So indeed, maximum |T| ≤ max_{c} |B_original(c,R)|. And B_original(c,R) itself is a connected induced subgraph with diameter ≤ 2R (since all vertices within distance R from c; the farthest two could be up to 2R apart). So it's a valid candidate. So equality holds. So for even K, the optimal is max over vertices of ball size.
For odd K: K = 2R+1. For any tree T with diameter ≤ 2R+1, the center is an edge (if diameter odd) or a vertex (if diameter less). If diameter ≤ 2R (which is also ≤ 2R+1), then there exists a vertex c with eccentricity ≤ R. Then for that vertex c, we can consider an edge (c, v) where v is any neighbor (or maybe c itself) to fit the union condition? Actually the condition for odd K using edge centers: T ⊆ B_original(c,R) ∪ B_original(v,R) for some edge (c,v)? But if T's diameter is ≤ 2R, then we could take any neighbor v? Would T be a subset of B_original(c,R) ∪ B_original(v,R)? Since T ⊆ B_original(c,R) (because all vertices within R of c). Then T ⊆ B_original(c,R) ∪ B_original(v,R) trivially, because T is contained in the first ball. So the union of balls around an edge also contains T. However, we need to guarantee that the optimal over edges includes the case where the tree is actually centered at a vertex. But B_original(c,R) is a subset of B_original(c,R) ∪ B_original(v,R) for any neighbor v, and the union might be larger than B_original(c,R) (including extra vertices), but that union might have diameter > K? Let's check: If we take an edge (c,v) and consider the union of balls radius R around c and v, this set S might have diameter up to 2R+1 (since it's the typical structure). If we add extra vertices from the ball around v, it could increase the diameter, but the set S as defined is a specific set (the union of both balls). Its diameter could be exactly 2R+1, which is allowed. So S is a candidate, and its size may be larger than B_original(c,R). So the maximum over edges of |S(u,v)| is at least as large as max over vertices of |B(v,R)|? Not necessarily; ball around a vertex might be larger than any union around an edge? Let's compare: For a given vertex c, B(c,R) might be large. For an edge (c,v), S(c,v) = B(c,R) ∪ B(v,R) is at least B(c,R), so it's at least as big. So the max over edges is at least the max over vertices. So considering edges suffices.
But we must ensure that any tree T with diameter ≤ 2R+1 is contained in S(u,v) for some edge (u,v) that is the central edge of T (or something). If T has diameter ≤ 2R, we already argued it is contained in B(c,R) for some vertex c. But B(c,R) is contained in S(c,v) for any neighbor v, but that S(c,v) might include extra vertices that are not in T, but that doesn't affect the containment of T. So indeed T is a subset of some S(u,v) (just pick u=c and v any neighbor; if c is leaf maybe no neighbor? But any vertex has at least one neighbor unless N=1, but N≥2). So T is contained in S(u,v). So |T| ≤ |S(u,v)|. So maximum over edges gives an upper bound. And the maximum over edges is achievable because S(u,v) itself is a valid tree with diameter ≤ 2R+1 (provided that the union is connected and has diameter ≤ 2R+1). So the optimum is max over edges.
Thus the solution is correct.
Now we need to compute distances. Since N ≤ 2000, we can do BFS from each vertex. Alternatively, we can compute distances using DFS because tree, we can compute distance between any two nodes by rooting and using LCA, but simpler: BFS from each node O(N^2). Let's compute adjacency list. For each vertex s, run DFS to compute dist[s][v] (since tree, just a DFS). Use recursion or stack. Complexity O(N^2). Then compute max_keep.
Implementation details:
If K is even:
R = K//2
max_keep = 0
For each vertex v:
count = number of u such that dist[v][u] <= R
max_keep = max(max_keep, count)
If K is odd:
R = K//2 (floor division)
max_keep = 0
For each edge (a,b) (given in input):
count = 0
For each vertex u:
if dist[a][u] <= R or dist[b][u] <= R: count++
max_keep = max(max_keep, count)
Also we might consider the case where the tree is a single vertex? But N>=2, so edges exist.
Output N - max_keep.
Check sample 1: N=6, K=2 (even, R=1). Compute distances? The tree: edges: 1-2, 2-3, 2-4, 1-6, 6-5. Graph: 2 connected to 1,3,4; 1 connected to 2,6; 6 connected to 1,5. So distances: From vertex 1: to 1:0, 2:1, 3:2, 4:2, 6:1, 5:2. So B(1,1) includes {1,2,6} -> size 3. Vertex2: distances: 2-0,1-1,3-1,4-1,6-2,5-3? Actually 2 to 6: 2-1-6 =2, to 5: 2-1-6-5=3. So B(2,1): {2,1,3,4} size 4. Vertex3: distances: 3-0,2-1,4-2,1-2,6-3,5-4? Actually 3 to 4:3-2-4=2, so B(3,1): {3,2}? plus maybe? 3 to 2 distance1, to 1 distance2, to 4 distance2, to6 distance3, to5 distance4? So size2. Vertex4 similar size2. Vertex5: distances:5-0,6-1,1-2,2-3,3-4,4-4? So B(5,1) = {5,6} size2. Vertex6: distances:6-0,1-1,5-1,2-2,3-3,4-3? So B(6,1) = {6,1,5} size3. Max = 4. So max_keep = 4, N - max_keep = 2. matches sample output 2.
Sample2: N=6, K=5 (odd? K=5 is odd, R=2). We need to consider edges. Let's compute all distances quickly. We'll compute manually later. But expected output 0, so max_keep should be 6. So there exists an edge whose union of radius2 balls covers all vertices. Let's check: For edge (1,2) maybe? Compute distances: For each vertex u, check if dist to 1 <=2 or dist to 2 <=2. Distances from 1: 1:0,2:1,6:1,5:2,3:2 (1-2-3), 4:2 (1-2-4) => all <=2? Actually 3 and 4 have distance2 from1? Path:1-2-3 length2, yes. So B(1,2) already includes all vertices. So max_keep =6. So answer 0. Good.
Thus solution seems correct.
But we must be careful: The union of balls for an edge (u,v) with radius R may include vertices that are at distance > R from u but ≤ R from v. However, if there is a vertex w such that dist(w,u) > R and dist(w,v) > R, it's not included. So we count only those.
Time complexity: O(N^2) for distances + O(N^2) for checking each edge? Number of edges = N-1 ≤1999. For each edge, we iterate over all N vertices to check condition => O(N * (N-1)) = O(N^2) as well, so total O(N^2). That's fine.
Memory: store distance matrix of size N x N, up to 2000^2 = 4e6 integers, which is okay (4 million ~ 16 MB if int). In Python, a list of lists of ints might be heavier but still manageable. However we could also compute distances on the fly? But simpler to compute matrix.
But we need to careful about recursion depth for DFS; N up to 2000, recursion depth could be up to 2000 if tree is a path; Python default recursion limit is 1000, so we need to either increase recursion limit or use iterative BFS/stack. I'll use BFS from each node using a queue (collections.deque) which is O(N) per node. BFS ensures no recursion issues. BFS from each node gives dist matrix.
Alternatively, we can compute distances using Floyd-Warshall? Not needed.
Implementation plan:
Read N, K.
Build adjacency list (0-indexed for convenience).
Compute dist = [[0]*N for _ in range(N)] using BFS from each node.
For s in range(N):
dist[s] = [-1]*N
queue = deque([s])
dist[s][s] = 0
while queue:
u = queue.popleft()
for v in adj[u]:
if dist[s][v] == -1:
dist[s][v] = dist[s][u] + 1
queue.append(v)
If K % 2 == 0:
R = K//2
max_keep = max( sum(1 for u in range(N) if dist[v][u] <= R) for v in range(N) )
else:
R = K//2
max_keep = 0
For each edge (a,b) from input (or we can iterate over edges from adjacency list; but need original indices? We'll store edges list as (ai-1, bi-1) from input.
For each (a,b):
cnt = 0
for u in range(N):
if dist[a][u] <= R or dist[b][u] <= R:
cnt += 1
max_keep = max(max_keep, cnt)
Output N - max_keep.
That's it.
But wait: Is it always optimal to keep the entire ball (or union) as we claim? Let's test a tricky case: Consider K=1 (odd? Actually K=1 is odd, R = floor(1/2)=0). For K=1, diameter ≤ 1 means the tree can have at most 2 vertices (since a tree with >2 vertices would have diameter at least 2). Actually a tree with diameter 1 is just a single edge (2 vertices). For K=1, the optimal subtree can be at most size 2. Our method for odd K: consider each edge (u,v) with R=0. The union of balls of radius 0 around u and v is {u, v} (since only vertices within distance 0 from u is u itself, similarly v). So size 2. So max_keep = 2 if such edge exists (N>=2). So answer = N - 2, i.e., we need to remove N-2 vertices. That seems correct: you can only keep an edge; all other vertices must be removed. Could there be a better solution by keeping a single vertex? That would be size 1, not better. So okay.
For K=2 (even, R=1): ball radius 1 around a vertex includes the vertex and its immediate neighbors. Could there be a subtree of diameter 2 that is larger than any such ball? For example, consider a tree that is a path of length 2: vertices 1-2-3. The ball around vertex 2 (center) includes all three vertices, size 3, diameter = 2 (max distance 2 between 1 and 3). That's the whole tree. So max_keep=3. Could there be a subtree with diameter 2 that includes also vertex 4 connected to 2? Actually if we add vertex 4 as neighbor of 2, then ball around 2 includes {1,2,3,4} size 4, diameter? distance between 1 and 3 is 2, between 1 and 4 is 2, between 3 and 4 is 2? Actually 3 and 4 are both neighbors of 2, so distance=2, so diameter=2, okay. So ball is optimal. Could we have a subtree like {1,2,4}? That's also within ball. So indeed max is ball.
Now consider a tree with a "dumbbell": two central nodes connected by an edge, each with many leaves. For K=3 (odd, R=1). The optimal union around that edge includes all leaves of both central nodes, since leaves are distance 1 from their central node. So it captures all vertices. That is optimal if the whole tree has diameter 3? Let's check: If each central node has many leaves, then distance between a leaf on left (say L1) and a leaf on right (R1) = L1 - left_center - right_center - R1 = 3 edges, so diameter = 3. So whole tree is valid, so we keep all vertices. Our union captures all vertices. So good.
What about a more complex tree where the optimal subtree might be something like a path that is not fully contained in any ball union of radius R? For K=3, R=1. Consider a tree that is a path of length 4: nodes 1-2-3-4-5. The whole tree diameter=4 >3, so not allowed. The maximum subtree with diameter ≤3 is size 4 (nodes 1-2-3-4 or 2-3-4-5). For edge (2,3): union of radius1 balls: B(2,1) = {1,2,3}, B(3,1) = {2,3,4}, union = {1,2,3,4} size4. So captured. For edge (3,4): union = {2,3,4,5}. So it's captured. So indeed.
Thus solution seems solid.
But we should also consider the possibility that for odd K, the best center might be a vertex instead of an edge? However, the ball around a vertex with radius R (which is floor(K/2)) would have diameter ≤ 2R ≤ K-1? Actually 2R = K-1 < K, so it's also a valid subtree. But its size may be smaller than some union. So max over edges already covers that (since ball around a vertex is a subset of union with any neighbor). So it's okay.
Now we must be careful about the input: The tree edges are given. We will store edges as (a-1, b-1) for later use in odd case. But also we can generate edges from adjacency list. However, we need to iterate over edges. Since N up to 2000, we can just use the edges from input (store them). So we don't need to extract from adjacency.
Now complexity: O(N^2) BFS for distances: N BFS, each BFS visits N nodes and edges. That's O(N^2) because each BFS processes each edge (N-1 edges) but that's also O(N) per BFS, so total O(N^2). That's fine.
But note: BFS from each node will produce a distance matrix of shape N x N. We can fill it row by row. That uses memory O(N^2). For N=2000, that's 4 million integers. In Python, if we use list of lists of ints, each int is 28 bytes (Python object) if we use Python ints, but actually list of ints each int is an object, memory huge (like 4M * 28 = 112 MB plus list overhead). That could be heavy but possibly okay? Actually Python int overhead is about 28 bytes (in CPython). 4 million ints would be ~112 MB, plus list overhead (list of 2000 lists each with 2000 ints) might push >150 MB, which might be borderline for typical memory limits (maybe 256 MB). But we can try to reduce memory by using array module or using list of arrays of short ints? Since distances up to N-1 (max 1999), they fit in 16-bit integer. However Python's standard list uses Python objects. To reduce memory, we could use a list of bytearray or array('H')? But then we need to store distances for BFS? Alternatively, we could avoid storing the full matrix and compute counts on the fly: For each vertex v, we need distances from v to all others. For even K, we can compute BFS from each v and count directly, without storing all distances simultaneously. For odd K, for each edge (a,b), we need distances from a and b to all vertices. We could compute BFS from each vertex and store the distances as an array temporarily, but we need distances from both a and b to evaluate each edge. We could precompute all distances and store them in a compact form. Or we could compute BFS from each vertex, store the distance list (as a list of ints) and keep them all in a list of lists. With N=2000, as said, memory might be high but possibly within 256 MB? Let's calculate more precisely: In Python, each integer is a PyObject, 28 bytes (on 64-bit). So 20002000=4,000,000 ints => 112,000,000 bytes (≈107 MB). Each inner list has overhead ~82000? Actually list object overhead is about 56 bytes plus pointer array of 2000 pointers (8 bytes each) => 56+16000 ≈ 16056 bytes per inner list. 2000 such lists => about 32 MB. So total ~139 MB. Plus other structures: adjacency list etc. Might still be okay if memory limit is 1 GB? Usually AtCoder (maybe this problem from AtCoder) has memory limit 1024 MB? Actually AtCoder typical memory limit is 1024 MB for Python? But not sure. The problem is from AtCoder ABC 267? Actually I recall a problem "ABC 267 F" maybe? Not sure. However, N=2000 is small; even 150 MB is acceptable in many contests (like AtCoder often 1024 MB for Python). But to be safe, we can optimize memory by using array('H') or a list of bytearray? Since max distance ≤ N-1 ≤ 1999 fits in 16 bits. We can store distances as a list of array('H') which uses 2 bytes per element. 4 million * 2 = 8 MB, much better. But implementing BFS and filling such arrays may be a bit more cumbersome but doable.
Alternatively, we can compute distances on the fly for each edge in odd case: For each edge (a,b), we could run BFS from a and from b separately, compute distances to all vertices, then count union. That would be O(N * E) = O(N^2) BFS calls? Actually if we do BFS from each edge's endpoints separately, that would be O(N * (N-1) * N) = O(N^3) which is too high. So we need precomputed distances.
We could precompute distances and store as list of lists of ints; memory might be okay. But I'd like to be efficient.
Another idea: For each vertex, we can compute its distance to all others and store as a list of ints. Instead of storing all at once, we could store them and then later use them. But we need them for all edges. So we need to access dist[a] and dist[b] for each edge. So we need to keep all distance lists. So we must store them.
We can store dist as a list of lists of ints. 4e6 ints ~ 112 MB, plus overhead. Possibly acceptable, but I'm not entirely comfortable. However, many Python solutions for N=2000 do this and pass. But I'd like to be safe by using array module.
But there's also an alternative approach: For each center (vertex or edge), we can compute the kept vertices by performing a BFS limited to radius R? Actually we can compute the ball size for a vertex by BFS until distance R, but for edge union we could compute the number of vertices within distance R from either endpoint. That can be done by running BFS from both endpoints and merging. But to evaluate all vertices or edges, we would need to run BFS from each vertex/edge, leading to O(N^2) total anyway. But we could compute BFS from each vertex once and store distances, so we already have that.
Given N=2000, I'll implement with full distance matrix using list of lists. To reduce memory, we can use list of array('H') or list of bytearray? But bytearray only stores up to 255, but distances up to 1999 >255, so need 2 bytes. Use array('H') (unsigned short). But we need to assign values; BFS can fill an array of ints first then convert? Simpler: Use a list of lists of ints; it's likely okay.
Check typical AtCoder Python memory limit: I think it's 1024 MB for most problems. So 150 MB is fine. But sometimes memory limit is 256 MB; still okay? 150 < 256. So I'll proceed.
Edge case: K might be 0? Constraint says 1 ≤ K ≤ N-1, so K≥1. So R≥0.
Now let's double-check with odd K: For K=1, R=0. Union of balls of radius 0 around each edge = just the two endpoints. So max_keep ≤ 2. That's correct.
For K=3, R=1, union of balls radius1 around edge.
Now we should also think about if the tree is huge and the ball may include many nodes. But that's fine.
Thus the solution appears correct.
But we must verify the necessity proof more formally: For any connected induced subtree T (i.e., a set of vertices S that is connected in the original tree), its diameter d ≤ K. For even K=2R, there exists a vertex c in T such that distance from c to any other vertex in T ≤ R (by tree property: the center of T is either a vertex or an edge, but if d even, center is a vertex). However, it's possible that d is odd and less than K? For K even, if d is odd, then d ≤ K-1, which is odd, but we need d ≤ K. Could T have odd diameter and still satisfy d ≤ K (which is even)? Yes, e.g., K=4, d=3 ≤4. In that case, does there exist a vertex c such that all vertices are within distance ≤ floor(K/2)=2? Since radius r = ceil(d/2). If d=3, radius = 2. So there exists a vertex c with eccentricity 2. So all vertices within distance 2 from c. So indeed all vertices within distance R=2 from c. So even if d is odd, it's still ≤2R? Actually if R=2, then 2R=4, d=3 ≤4. But we claim that all vertices are within distance R from some vertex? For d=3, radius=2, yes. So it holds. So for even K, any tree with diameter ≤ 2R has radius ≤ R. Indeed because radius = ceil(d/2) ≤ ceil(2R/2)=R. So yes. So there always exists a vertex c with eccentricity ≤ R. So the ball condition holds.
Thus the solution is correct.
Now implement.
Implementation details:
We'll store vertices 0-indexed.
Pseudo-code:
def solve():
import sys
sys.setrecursionlimit(1<<25)
input = sys.stdin.readline
N, K = map(int, input().split())
adj = [[] for _ in range(N)]
edges = []
for _ in range(N-1):
a,b = map(int, input().split())
a-=1; b-=1
adj[a].append(b)
adj[b].append(a)
edges.append((a,b))
from collections import deque
dist = [[-1]*N for _ in range(N)]
for s in range(N):
d = dist[s]
d[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if d[v] == -1:
d[v] = d[u] + 1
q.append(v)
if K % 2 == 0:
R = K//2
max_keep = 0
for v in range(N):
cnt = 0
for u in range(N):
if dist[v][u] <= R:
cnt += 1
if cnt > max_keep:
max_keep = cnt
else:
R = K//2
max_keep = 0
for a,b in edges:
cnt = 0
da = dist[a]
db = dist[b]
for u in range(N):
if da[u] <= R or db[u] <= R:
cnt += 1
if cnt > max_keep:
max_keep = cnt
print(N - max_keep)
That's it.
But wait, there might be a nuance: For odd K, we consider each edge (u,v). However, what if the optimal subtree has diameter ≤ K but its center edge is not present in the original tree? But the tree is the original tree, and the subtree is induced, so its vertices and edges are a subset of original. The center edge of the subtree must be an edge that connects two vertices in the subtree. However, that edge may not be an edge in the original tree? But if two vertices are adjacent in the subtree, they must be adjacent in the original tree because the induced subgraph includes edges that exist in the original tree. So the subtree's edges are a subset of the original edges. Therefore the central edge of the subtree is an edge that exists in the original tree (since both endpoints are in the subtree and they are adjacent). So indeed it's one of the original edges. So our iteration over edges of the original tree covers all possible central edges of any subtree.
Thus the approach is sound.
Now test with some custom cases.
Case: N=2, K=1 (odd). Tree: 1-2. Distances: from 1: [0,1]; from 2: [1,0]. R=0. Edge (1,2): union of balls radius0: {1,2} size2 => max_keep=2, answer 0. But can we keep any tree? Yes, we can keep both vertices, diameter=1 ≤1, so we remove 0. So correct.
Case: N=2, K=2 (even). R=1. Ball around vertex1: vertices within distance1: both (distance0 and1) => size2. So max_keep=2, answer0. Indeed whole tree diameter=1 ≤2, so remove0.
Case: N=3, path 1-2-3, K=1. R=0 (odd). Edge (1,2): union radius0 => {1,2} size2. Edge (2,3): {2,3} size2. So max_keep=2, answer=1. Indeed we can keep only an edge, remove the other vertex. That seems optimal because a subtree with diameter ≤1 can only be a single edge or single vertex. Two vertices gives 2, one vertex gives 1, so best is 2.
Case: N=3, path, K=2 (even). R=1. Ball around vertex2: all three within distance1? distances: 2 to 1:1, to3:1, so size3 => max_keep=3, answer0. Whole tree diameter=2 ≤2, so remove0.
Case: N=3, star (center1, leaves2,3). Actually that's the same as path? Actually a star with center 1 and leaves 2,3 is exactly a tree with edges 1-2,1-3. Diameter =2. So same.
Now test a bigger random case to ensure no missing case.
But wait, we assumed that the optimal kept set is exactly the union of balls around an edge (or ball around vertex). However, consider the scenario where K is odd, and the optimal subtree T has diameter exactly 2R+1, but its center edge is (u,v). In the original tree, the union S(u,v) of balls radius R around u and v might contain vertices that are not in T. Could adding those extra vertices increase the diameter beyond K? Possibly if we add a vertex w that is within distance R from u but also far from v? Actually if w is within distance R from u, then adding w to T might increase the diameter: Suppose T already contains some leaf on v's side at distance R from v (so distance from that leaf to w could be up to R (leaf to v) + 1 + R (u to w) = 2R+1, which is exactly K, so still okay. However, what if there is a vertex w within distance R from u that is also distance R+1 from some vertex x in T? The farthest distance between any two vertices in S(u,v) is at most 2R+1, as argued earlier, because any two vertices are within distance 2R+1: if both near u, max 2R; both near v, max 2R; one near u one near v, max 2R+1. So S(u,v) itself has diameter ≤ 2R+1. So adding all such vertices does not exceed K. So S(u,v) is a valid subtree. Thus if T is optimal and T ⊆ S(u,v), then |T| ≤ |S(u,v)|, but S(u,v) is also valid, so the optimal must be at least |S(u,v)|, so actually |T| = |S(u,v)| if T is maximum. But could there be a case where |S(u,v)| is larger than any possible subtree? No, because S(u,v) is itself a subtree. So max over edges gives exactly the maximum.
Thus the solution is correct.
Now time complexity: O(N^2) BFS: For each source, BFS visits all nodes and edges. Since it's a tree, each BFS does O(N) operations. So O(N^2). The counting for even case: For each vertex, loop over N nodes, that's O(N^2). For odd: For each edge (N-1), loop over N nodes, O(N^2). So total O(N^2). With N=2000, that's about 4 million operations per phase, total maybe 12 million, which is very fast in Python.
Now we might also think about using BFS from each vertex and directly compute count, avoiding full matrix if memory concerns. But we already decided.
Sample2: N=6 K=5 odd => R=2. Edge (1,2): we saw all nodes within distance2 from 1 (distances: to 1:0,2:1,3:2,4:2,6:1,5:2) -> all ≤2, so union =6. So max_keep=6 -> answer0.
Works.
Now consider a potential tricky scenario: The tree may have long paths, and for odd K, the best edge might be somewhere in the middle. That's captured.
Now consider if K is large enough to include whole tree. For K >= diameter of original tree, then we can keep all vertices (remove 0). Our method: For even K, max ball size would be N because if K/2 >= radius? Actually if K is larger than diameter, then for even K, ball around some vertex with radius K/2 will include all vertices because the maximum distance from that vertex is at most diameter, which <= K, but not necessarily ≤ K/2? Wait, for even K, we require ball radius K/2. If the diameter D ≤ K, it's not necessarily true that there exists a vertex with eccentricity ≤ K/2. Example: N=3 path, diameter D=2, K=2 even, radius = 1, which equals K/2. That works. But if K=4, D=2, then K/2=2, and there exists a vertex with eccentricity ≤ 2 (actually eccentricity of center is 1 ≤2). So ball radius 2 includes all vertices. So max ball = N. So answer 0. For odd K, if K >= D, is there an edge such that union of balls radius floor(K/2) covers all? Since D ≤ K, but D could be even or odd. For instance, tree with D=2, K=3 (odd), R=1. Does there exist an edge such that all nodes within distance 1 from u or v? If the tree is a path of 3 nodes (1-2-3), D=2. For edge (2,3): B(2,1)={1,2,3}? Actually B(2,1) includes nodes at distance ≤1: {1,2,3}? 2 to 3 distance1, to1 distance1, so yes, includes all. So union = all nodes. For edge (1,2): B(1,1)={1,2}, B(2,1)={1,2,3}, union = all. So yes. If the tree is a star with center c and leaves, D=2, edge (c, leaf): B(c,1) includes all nodes (c and all leaves), union = all. So works. For D=1, K=3, R=1: The tree is a single edge? Actually D=1, N=2. Edge (u,v): B(u,1) includes both (distance from u to v is 1 ≤1, so includes v? Actually B(u,1) includes nodes with distance ≤1: u and v; B(v,1) similarly; union = both. So all nodes. So indeed if K >= D, there is always an edge that covers all? Consider D=3, K=3 (odd), R=1. The whole tree has diameter 3. Its central edge (u,v) satisfies that all nodes are within distance 1 of u or v? We proved earlier that for any tree with diameter ≤ 2R+1, there exists an edge such that every vertex is within distance R of u or v. So if D=3=2*1+1, then condition holds. So the central edge works. So our method will find N as max_keep.
Thus answer will be 0 when K is at least the diameter. But is it possible that K is less than diameter but the max_keep computed via our method may be less than the actual maximum? We've argued it's equal, but let's double-check with a potential counterexample: Suppose the tree is not "convex" in the sense that the ball around a vertex or union around an edge might include vertices that cause the diameter to exceed K? But we argued that the ball/union itself has diameter ≤ K. However, is it always true that the union of balls of radius R around two adjacent vertices has diameter ≤ 2R+1? Let's prove formally: Let S = { w | dist(w,u) ≤ R or dist(w,v) ≤ R }. Take any two nodes x,y ∈ S. Cases:
If both in B(u,R): dist(x,y) ≤ dist(x,u) + dist(u,y) ≤ R+R = 2R ≤ 2R+1.
If both in B(v,R): similarly ≤ 2R.
If x in B(u,R), y in B(v,R): dist(x,y) ≤ dist(x,u) + 1 + dist(v,y) ≤ R+1+R = 2R+1.
So diameter ≤ 2R+1. So indeed.
Thus S is valid.
Now, for even K, ball of radius R around a vertex: any two nodes x,y ∈ B(v,R): dist(x,y) ≤ dist(x,v)+dist(v,y) ≤ 2R = K, so diameter ≤ K.
Thus our candidate sets are valid.
Now the question: Could there be a valid subtree that is not a subset of any such ball/union? As argued, any valid subtree T (with diameter ≤ K) must satisfy the center condition: if K even, there exists a vertex c such that T ⊆ B_T(c,R) ⊆ B_original(c,R). So T is a subset of some ball (vertex). If K odd, there exists an edge (u,v) such that T ⊆ (B_T(u,R) ∪ B_T(v,R)) ⊆ (B_original(u,R) ∪ B_original(v,R)). So T is a subset of some union. So indeed T is contained in these sets. So size of T cannot exceed the size of that super set. And since the super set itself is valid, the maximum possible is exactly the maximum size of such super set. So our computation yields the optimum.
Thus the solution is correct.
Now let's implement.
Potential pitfalls:
Need to handle large recursion? Not using recursion, using BFS.
Input edges are given, we need to store them for odd case.
Use 0-indexing.
Now let's produce the final code.
But wait: There is a nuance: For K even, we assumed that the center vertex c is in T. However, c must be a vertex in T because it's the center of T. So c is part of T. In the original tree, B_original(c,R) includes c and all nodes within distance R from c. That set might include nodes not in T. But that's fine. So |T| ≤ |B_original(c,R)|. And |B_original(c,R)| is achieved by the set itself, which is a valid subtree. So max_keep = max_{c} |B_original(c,R)|.
But is it always true that B_original(c,R) is a subtree (connected induced)? Yes, as argued: it's connected because any node's path to c lies within the set. And it's induced: all edges between nodes in the set are present because they are edges of original tree; it's a subtree. So yes.
Thus final.
Now we can code.
Given N up to 2000, we can also use DFS instead of BFS for distances because it's a tree and we can compute distances using recursion with parent, but BFS is simple.
But we must compute distances from each source. We can also compute all-pairs distances by performing BFS from each node. That's fine.
Alternatively, we could compute the distances using DP: root the tree, compute depths and LCA, then compute distances in O(1) per pair after O(N log N) preprocessing. But O(N^2) is simpler.
Now we produce final answer.
Edge Cases:
N=2000, K=1999 (odd, R=999). For each edge, we need to check distances. The distance matrix might have values up to 1999. BFS from each node will compute distances.
N=2000, K=1 (odd, R=0). For each edge, we count nodes with dist from a <=0 or from b <=0 -> just a and b, so count = 2 for each edge. So max_keep = 2, answer = N-2. That seems plausible: we can only keep an edge, all others removed.
Now we should test with a random small tree to confirm.
Let's write a quick mental test: N=4, tree: 1-2-3-4 (path). K=3 (odd, R=1). Edges:
(1,2): B(1,1)={1,2}, B(2,1)={1,2,3} union={1,2,3} size3.
(2,3): B(2,1)={1,2,3}, B(3,1)={2,3,4} union={1,2,3,4} size4.
(3,4): B(3,1)={2,3,4}, B(4,1)={3,4} union={2,3,4} size3.
max=4, answer0. Whole tree has diameter 3 ≤3, so yes, we can keep all.
Now K=2 (even,R=1). Balls:
v1: {1,2} size2
v2: {1,2,3} size3
v3: {2,3,4} size3
v4: {3,4} size2
max=3, answer=1. Is that optimal? Can we keep 3 vertices with diameter ≤2? Yes, keep {1,2,3} or {2,3,4} gives diameter 2, size3. Could we keep 4 vertices? The whole tree diameter is 3 >2, so cannot. So answer 1 correct.
Now K=1 (odd,R=0). Edges: each union size2, max_keep=2, answer=2 (remove 2 vertices). Indeed we can keep at most an edge.
Now consider a tree where there is an edge (u,v) such that B(u,R) and B(v,R) have overlap, but maybe the maximum is achieved by a vertex ball when K odd? For instance, suppose K=3 (R=1), tree: star with center c and many leaves. Edge (c, leaf) union = all nodes, which is N. So that's fine. Suppose we have a tree where the best union is not larger than some vertex ball? That's okay, we still take max over edges, which will be at least vertex ball.
Now consider a tree where K odd, and the best union actually corresponds to an edge that is not necessarily the one that yields maximum number, but we iterate over all edges so we find it.
Thus solution is correct.
Now I'll produce final code.
Potential memory optimization: Instead of storing full NxN matrix as list of lists of ints, we can store as list of array('H') to reduce memory. But I'll keep list of lists for simplicity, given N=2000.
But I'll check memory: In Python, using list comprehension with integers, each row is a list of ints. The integers themselves are objects, memory heavy. I recall that in AtCoder, Python solutions often use such matrix for N=2000 and it's okay because memory limit is 1024 MB. However, sometimes they have memory limit 256 MB; still, 150 MB might be okay but could be near limit if there is additional overhead. To be safe, I can implement using array('H').
Let's explore: from array import array. We can create a list of arrays: dist = [array('H', [0])*N] not directly. Actually array('H', [0])*N replicates the array? But we need to assign values during BFS. We can create an array of length N with initial value maybe 65535? But we need to assign distances. We can use list for distances during BFS then convert? Simpler: Use list of lists.
But I'll try to reduce: Since we only need distances for each vertex, we could compute on the fly for odd case: For each edge (a,b), we need distances from a and b. If we precomputed distances from each vertex, we need them anyway. We could store distances as list of lists of ints. I'll go with that.
Alternatively, we could compute for each vertex its distance to all others and store as a list of ints. That is exactly the matrix.
Given typical AtCoder Python solutions, I've seen them store distances for N=2000 as list of lists and it's fine. I'll proceed.
But there is a catch: The BFS for each source using queue of integers. That's fine.
Now I'll code.
We can also precompute distances using Floyd-Warshall? Not needed.
Implementation:
def solve():
import sys
from collections import deque
input = sys.stdin.readline
N, K = map(int, input().split())
adj = [[] for _ in range(N)]
edges = []
for _ in range(N-1):
a,b = map(int, input().split())
a-=1; b-=1
adj[a].append(b)
adj[b].append(a)
edges.append((a,b))
# compute all-pairs distances
dist = [[-1]*N for _ in range(N)]
for s in range(N):
d = dist[s]
d[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if d[v] == -1:
d[v] = d[u] + 1
q.append(v)
if K % 2 == 0:
R = K // 2
max_keep = 0
for v in range(N):
cnt = sum(1 for u in range(N) if dist[v][u] <= R)
if cnt > max_keep:
max_keep = cnt
else:
R = K // 2
max_keep = 0
for a,b in edges:
da = dist[a]
db = dist[b]
cnt = 0
# loop over u
for u in range(N):
if da[u] <= R or db[u] <= R:
cnt += 1
if cnt > max_keep:
max_keep = cnt
print(N - max_keep)
Now we need to ensure we treat K even/odd correctly. For K odd, R = K//2 is floor division, which is correct.
Testing with given samples.
But wait: For K odd, we used R = K//2. For K=5, R=2. That matches earlier. For K=3, R=1. Good.
Now we should consider potential off-by-one: The diameter is number of edges on the path. If we have a ball radius R (max edges from center), then any two nodes in the ball are at most 2R edges apart. So if K=2R, then diameter ≤ 2R. If we have union of balls around an edge, the maximum distance is 2R+1. So with K=2R+1, it's okay.
Thus.
Now check edge case K=0? Not allowed.
Now let's test with a custom case: N=7, tree: 1-2-3-4-5-6-7 (path). K=4 (even, R=2). Balls: For vertex 4 (middle), distances: to ends: 4 to 1:3 >2? Actually path length: 1-2-3-4-5-6-7. Distances: 4 to 1 is 3, to 7 is 3. So B(4,2) includes nodes within distance2: {2,3,4,5,6} (distance: 4 to 2 =2, to 6=2) -> size5. For vertex 3: distances: to 1=2, to 7=4? 3 to 7: 3-4-5-6-7 =4, so B(3,2) includes nodes with distance ≤2: {1,2,3,4,5}? 3 to5 =2, so {1,2,3,4,5} size5. Vertex 5 similar. Vertex 2: distances: to 6=4 >2, so B(2,2) includes {1,2,3,4}? Actually 2 to 4=2, to5=3 >2, so {1,2,3,4} size4. So max_keep=5. So answer=2. Is it optimal? The whole tree diameter=6 >4. The best subtree with diameter ≤4: For a path, the longest induced subpath with length ≤4 edges (i.e., number of edges between extremes ≤4). The number of vertices in such a subpath is at most 5 (since edges=4 -> vertices=5). So indeed we can keep a contiguous segment of 5 vertices, e.g., 2-3-4-5-6 (diameter 4). So remove 2 vertices. So correct.
Now K=5 (odd, R=2). Edges: For edge (3,4): B(3,2) = {1,2,3,4,5}? Actually 3 to 6 is 3? 3-4-5-6 =3 >2, so not included. So B(3,2) includes {1,2,3,4,5}? Wait: 3 to 5 is 2, so yes 5 is included. 3 to 6 is 3, so not. So B(3,2) = {1,2,3,4,5}. B(4,2) = {2,3,4,5,6}. Union = {1,2,3,4,5,6} size6. That's all except 7 maybe? Actually includes 6? B(4,2) includes 6 (dist4-6=2), yes. So union = {1,2,3,4,5,6} size6. Edge (4,5): B(4,2)={2,3,4,5,6}, B(5,2)={3,4,5,6,7}? 5 to 2? 5-4-3-2 =3 >2, so B(5,2) = {3,4,5,6,7}. Union = {2,3,4,5,6,7} size6. Edge (2,3): B(2,2)={1,2,3,4}, B(3,2)={1,2,3,4,5} union={1,2,3,4,5} size5. Edge (5,6): similarly size5. Edge (6,7): B(6,2)={4,5,6,7}? Actually 6 to 4=2, to 3=3, so {4,5,6,7}? plus maybe? 6 to 2=4 >2, so only those. B(7,2)={5,6,7}? 7 to 5=2, to4=3, so {5,6,7}. Union = {4,5,6,7}? Actually union of B(6,2) and B(7,2) = {4,5,6,7} size4. So max_keep=6. So answer=1. Indeed, we can keep a subtree with diameter ≤5: e.g., keep all vertices except one endpoint, keeping 6 vertices, diameter = distance between 1 and 6? If we keep vertices 1-2-3-4-5-6, diameter =5 (1 to 6 distance 5). That's allowed (K=5). So we remove 1 vertex. So correct.
Now check if there is any scenario where the optimal subtree is not exactly a ball/union but a proper subset of such a set that is larger than any ball/union? That can't happen because any valid subtree is a subset of some ball/union (the one centered at its center), and the ball/union itself is a valid subtree, so if the subtree is optimal, the ball/union must be at least as large, but if the ball/union is larger than the subtree, then that ball/union would be a better solution, contradicting optimality. So optimal must be exactly such a set.
Thus solution stands.
Now final code.
But wait, there's a subtlety: When we compute the ball around a vertex v, we include all nodes with distance ≤ R. This set includes nodes that might not be connected? Actually they are connected as argued. But we need to ensure that the induced subgraph is indeed a tree (connected). For a ball in a tree, it's connected because for any node x in the ball, the path from v to x is within the ball (since all intermediate nodes have distance ≤ dist(x) ≤ R). However, does that guarantee that the induced subgraph on the ball is exactly that set of nodes and the edges among them? The induced subgraph includes all edges between nodes in the set. Since the original tree is a tree, the induced subgraph is a subtree (a connected subgraph) if the set is connected in the original tree. It might not be a tree if there is a cycle? But original tree has no cycles, so induced subgraph also has no cycles. So it's a tree.
Thus all good.
Now time to code.
I'll produce the final answer. ```python
import sys
from collections import deque
def solve() -> None:
input = sys.stdin.readline
N, K = map(int, input().split())
adj = [[] for _ in range(N)]
edges = []
for _ in range(N - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
adj[a].append(b)
adj[b].append(a)
edges.append((a, b))
code
# ----- all-pairs distances -----
dist = [[-1] * N for _ in range(N)]
for s in range(N):
d = dist[s]
d[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if d[v] == -1:
d[v] = d[u] + 1
q.append(v)
# ----- decide the answer -----
if K % 2 == 0: # even K -> vertex centred ball
R = K // 2
best = 0
for v in range(N):
cnt = 0
dv = dist[v]
for u in range(N):
if dv[u] <= R:
cnt += 1
if cnt > best:
best = cnt
else: # odd K -> edge centred union of two balls
R = K // 2
best = 0
for a, b in edges:
da = dist[a]
db = dist[b]
cnt = 0
for u in range(N):
if da[u] <= R or db[u] <= R:
cnt += 1
if cnt > best:
best = cnt
print(N - best)