#!/usr/bin/env python3
from collections import namedtuple, deque
import sys

# Node = namedtuple('Node', ('min_distance', 'parents', 'children'))
class Node(object):
  def __init__(self, min_distance, parents, children):
    self.min_distance = min_distance
    self.parents = parents
    self.children = children

graph = dict()  # Node name -> Node

MAX_LENGTH = 3
MAX_PARENTS = 3  # TODO: fix this to not lose data

prefix = list()
lines = list()
suffix = list()

first_node = None
for line in sys.stdin:
  if ' -> ' in line:
    left, right = line.strip().split(' -> ')
    if left not in graph:
      if first_node is None:
        graph[left] = Node(0, list(), list())
        first_node = left
      else:
        continue
    if graph[left].min_distance > MAX_LENGTH:
      continue
    graph[left].children.append(right)
    if right not in graph:
      graph[right] = Node(MAX_LENGTH + 1, list(), list())
    if len(graph[right].parents) < MAX_PARENTS or True:
      graph[right].parents.append(left)
      graph[right].min_distance = min(graph[right].min_distance, graph[left].min_distance + 1)
    elif graph[left].min_distance + 1 < graph[right].min_distance:
      graph[right].min_distance = graph[left].min_distance + 1
      graph[right].parents = graph[right].parents[1:] + [left]
    lines.append(line)
  elif '"//' in line:
    lines.append(line)
  elif not first_node:
    prefix.append(line)
  else:
    suffix.append(line)

frontier = deque()
for name, node in graph.items():
  if len(node.children) == 0 and node.min_distance < MAX_LENGTH:
    frontier.append(name)
if len(frontier) > 1:
  sys.stderr.write('\n' + ', '.join(frontier) + '\n')

visited = set()
while frontier:
  top = frontier.popleft()
  if top in visited:
    continue
  visited.add(top)
  top_node = graph[top]
  for parent in top_node.parents:
    frontier.appendleft(parent)

pruned_graph = dict()
for name, node in graph.items():
  if name in visited:
    pruned_graph[name] = node

for line in prefix:
  sys.stdout.write(line)
for line in lines:
  if ' -> ' in line:
    left, right = line.strip().split(' -> ')
    if left in pruned_graph and right in pruned_graph:
      sys.stdout.write(line)
  elif '"//' in line:
    node = line.strip()
    if node in pruned_graph and node in pruned_graph:
      sys.stdout.write(line)
for line in suffix:
  sys.stdout.write(line)

sorted_by_parents = list(sorted((len(node.parents), name, node) for name, node in pruned_graph.items()))

# for parents, name, node in reversed(sorted_by_parents):
#   print(parents, name, node)

# print(pruned_graph)
