import Control.Applicative
import Control.Monad

data BTree = BEmpty | BNode BTree BTree
instance Show BTree where
  show BEmpty = ""
  show (BNode l r) = '(' : show l ++ ',' : show r ++ ")"

parse ss = let (t,_) = psub ss in t
  where
    psub ('(':s1) = let (left, (',':s2)) = psub s1 in let (right, (')':s3)) = psub s2 in (BNode left right, s3)
    psub s = (BEmpty, s)

btintersection BEmpty _ = BEmpty
btintersection _ BEmpty = BEmpty
btintersection (BNode l1 r1) (BNode l2 r2) = BNode (btintersection l1 l2) (btintersection r1 r2)

btunion BEmpty r = r
btunion l BEmpty = l
btunion (BNode l1 r1) (BNode l2 r2) = BNode (btunion l1 l2) (btunion r1 r2)

solve ["i", lt, rt] = btintersection (parse lt) (parse rt)
solve ["u", lt, rt] = btunion (parse lt) (parse rt)

main = map (solve . words) . lines <$> getContents >>= mapM_ print
