Codeforces Round 1133 (Div. 1, Div. 2) is coming soon! Register here. ×

A2SV G6 — Round #14 (Editorial)

Revision en1, by A2SV_Group6, 2025-05-12 15:41:30

Here is the contest link.

A. Funny Game

Hint
Solution
Code

B. Metshaf Exchange

Problem Summary
Hint 1

Brute Force Solution

Solution 1
Code 2
Solution 2
Code 2

Optimal Solution

Hint
Solution
Code

C. Destroy

D. Masha and The Bear

E. Wide, Wide Graph

Hint
Solution

”Code”

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()

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en11 English A2SV_Group6 2025-05-13 23:26:19 0 (published)
en10 English A2SV_Group6 2025-05-13 23:24:42 12
en9 English A2SV_Group6 2025-05-13 23:20:14 3859
en8 English A2SV_Group6 2025-05-13 10:13:39 3655
en7 English A2SV_Group6 2025-05-12 15:54:24 12 Tiny change: 'nting.\n\n\n<spoil' -> 'nting.\n\n</spoiler>\n\n<spoil'
en6 English A2SV_Group6 2025-05-12 15:53:21 186
en5 English A2SV_Group6 2025-05-12 15:47:57 38
en4 English A2SV_Group6 2025-05-12 15:45:53 12 Tiny change: 'spoiler>\n' -> 'spoiler>\n</spoiler>\n'
en3 English A2SV_Group6 2025-05-12 15:45:04 7
en2 English A2SV_Group6 2025-05-12 15:43:52 30 Tiny change: '`python3\nfrom col' -> '`python3\n\nfrom col'
en1 English A2SV_Group6 2025-05-12 15:41:30 9867 Initial revision (saved to drafts)