Aggregate routes

Providers announce as few routes as possible. Merge neighbouring networks into one shorter prefix.

What to build

A program that shrinks a list of networks to the smallest list that covers exactly the same addresses.

Requirements

  • Remove duplicates and networks that are inside another network of the list.
  • Merge two networks of the same prefix length p into one of length p − 1 when they are neighbours and together form one aligned block. Repeat until no more merges are possible.
  • Print the result sorted by address, one address/prefix per line.

Input

A line with n, then n networks address/prefix, each written with its host bits 0.

Output

The networks left, one per line.

Constraints

1 ≤ n ≤ 50; every prefix is from 1 to 32.

Example

Input:

2
10.1.2.0/24
10.1.3.0/24

Output:

10.1.2.0/23

Why it works

Two aligned neighbours of the same size make exactly one block of twice the size, so replacing them loses nothing and shortens the table. Removing contained networks and repeating the merges gives the smallest list.

Examples

Example 1 · Input
2
10.1.2.0/24
10.1.3.0/24
Expected output
10.1.2.0/23
Example 2 · Input
2
10.1.1.0/24
10.1.2.0/24
Expected output
10.1.1.0/24
10.1.2.0/24

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Convert each network to (start number, prefix length). First drop duplicates and networks that lie inside another network in the list.

Hint 2

Sort by start. Two neighbours merge when they have the same prefix p, the first starts at a multiple of 2 ** (33 - p), and the second starts right after the first (start + 2 ** (32 - p)).

Hint 3

After a merge the new, shorter prefix may merge again, so repeat until nothing changes. Print sorted by start.

Solution

Show one correct solution (try it yourself first)
def to_number(ip):
    n = 0
    for part in ip.split("."):
        n = n * 256 + int(part)
    return n

def to_ip(n):
    return ".".join(str((n >> s) & 255) for s in (24, 16, 8, 0))

n = int(input())
nets = set()
for _ in range(n):
    ip, p = input().strip().split("/")
    nets.add((to_number(ip), int(p)))
inside = set()
for s, p in nets:
    for s2, p2 in nets:
        if p2 < p and s >> (32 - p2) == s2 >> (32 - p2):
            inside.add((s, p))
nets = nets - inside
changed = True
while changed:
    changed = False
    ordered = sorted(nets)
    for i in range(len(ordered) - 1):
        s, p = ordered[i]
        s2, p2 = ordered[i + 1]
        size = 2 ** (32 - p)
        if p == p2 and p > 1 and s % (2 * size) == 0 and s2 == s + size:
            nets.discard((s, p))
            nets.discard((s2, p2))
            nets.add((s, p - 1))
            changed = True
            break
for s, p in sorted(nets):
    print(to_ip(s) + "/" + str(p))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Routing tables and longest prefix match →