A learning switch

A switch learns from the source of each frame and decides from the destination.

What to build

A program that runs a learning switch over a list of frames and prints what it does with each.

Requirements

  • For each frame, first learn: the source is behind the port it arrived on (a host that moves gets its entry updated).
  • Then decide: destination ff (broadcast) or not in the table gives flood; a destination behind the arrival port gives filter; any other known destination gives forward P with its port P.
  • After all frames, print table lines NAME -> port P in alphabetical order of NAME.

Input

A line with n, then n lines src dst port.

Output

One action line for each frame, then the table lines.

Constraints

1 ≤ n ≤ 100. Names have no spaces; the name ff is never a source.

Example

Input:

5
A B 1
B A 2
C A 3
A C 1
B ff 2

Output:

flood
forward 1
forward 1
forward 3
flood
A -> port 1
B -> port 2
C -> port 3

Why it works

Learning from the source means a reply teaches the switch where the first sender is. Forwarding only to the known port keeps the other ports quiet, and flooding is the safe fallback when the switch does not know.

Examples

Example 1 · Input
5
A B 1
B A 2
C A 3
A C 1
B ff 2
Expected output
flood
forward 1
forward 1
forward 3
flood
A -> port 1
B -> port 2
C -> port 3
Example 2 · Input
3
A B 1
A B 1
B A 1
Expected output
flood
flood
filter
A -> port 1
B -> port 1

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

Hints

Hint 1

Use a dict from name to port. Learn first: table[src] = port.

Hint 2

A broadcast (destination ff) or an unknown destination is flooded.

Hint 3

If the destination's port is the port the frame came in on, there is nothing to do: print filter.

Solution

Show one correct solution (try it yourself first)
n = int(input())
table = {}
for _ in range(n):
    src, dst, port = input().split()
    port = int(port)
    table[src] = port
    if dst == "ff" or dst not in table:
        print("flood")
    elif table[dst] == port:
        print("filter")
    else:
        print("forward", table[dst])
for name in sorted(table):
    print(name, "-> port", table[name])

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

Lesson: Ethernet, MAC addresses and switches →