Here is the contest link.
A. Funny Game
B. Metshaf Exchange
Brute Force Solution
Optimal Solution
C. Destroy
D. Masha and The Bear
E. Wide, Wide Graph
In a tree, there's a unique path between any two nodes. So we can define the "distance" easily using BFS or DFS.
Let’s fix a special node the farthest node from any random node (say, node $$$0$$$). From that, perform BFS to find the node furthest from it this gives one endpoint of the diameter. Do a final BFS from this endpoint to get the actual diameter and each node’s distance from it. We then compute the maximum distance for each node from either endpoint of the diameter. If the maximum distance of a node is less than $$$k$$$, then this node becomes isolated in $$$Gk$$$ since no other node is at distance ≥ $$$k$$$.
Hence, for each $$$k$$$, we count how many nodes become isolated (i.e., their max distance $$$k$$$, and increment the number of components accordingly. This gives an $$$O(n)$$$ solution using just a few BFS traversals and basic counting.
def bfs(tree, start): n = len(tree) dist = [-1] * n dist[start] = 0 q = deque([start]) while q: node = q.popleft() for neighbor in tree[node]: if dist[neighbor] == -1: dist[neighbor] = dist[node] + 1 q.append(neighbor) return dist
def main(): n = int(input())
tree = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
# Convert to 0-based index
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
# Step 1: BFS from arbitrary node (0) to find one endpoint of diameter
d1 = bfs(tree, 0)
far1 = d1.index(max(d1))
# Step 2: BFS from far1 to get distances and find farthest point (diameter)
d2 = bfs(tree, far1)
diameter = max(d2)
far2 = d2.index(diameter)
# Step 3: BFS from far2 to get second set of distances
d3 = bfs(tree, far2)
# For each node, take the maximum distance to either end of diameter
max_dist = [max(d2[i], d3[i]) for i in range(n)]
# Count how many nodes have max_dist < k
isolated_count = [0] * (n + 2)
for d in max_dist:
isolated_count[d] += 1
result = [1] # G_1 has 1 component (the whole tree)
for k in range(2, n + 1):
if k > diameter:
result.append(n)
else:
result.append(result[-1] + isolated_count[k - 1])
print(' '.join(map(str, result)))main()
```



