module Main where
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.List
import qualified Text.Printf
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString as BC

import System.IO

------------------------------------------

data Tr = Em | Br Tr Tr
  deriving (Show, Eq)

parse :: String -> (Tr, String)
parse "" = (Em, "")
parse ('(':xs) =
  let (lt, ',':xs') = parse xs
      (rt, ')':xs'') = parse xs' in (Br lt rt, xs'')
parse xs = (Em, xs)

unparse :: Tr -> String
unparse Em = ""
unparse (Br lt rt) = "(" ++ unparse lt ++ "," ++ unparse rt ++ ")"

uni :: Tr -> Tr -> Tr
uni Em Em = Em
uni lt Em = lt
uni Em rt = rt
uni (Br llt lrt) (Br rlt rrt) = Br (uni llt rlt) (uni lrt rrt)

intersec :: Tr -> Tr -> Tr
intersec Em Em = Em
intersec lt Em = Em
intersec Em rt = Em
intersec (Br llt lrt) (Br rlt rrt) = Br (intersec llt rlt) (intersec lrt rrt)

main :: IO ()
main = do
  eof <- isEOF
  if eof then return ()
  else do
  [cmd, xs, ys] <- words <$> getLine
  let (xt, _) = parse xs
      (yt, _) = parse ys
      ans = if cmd == "i" then intersec xt yt else uni xt yt
  putStrLn $ unparse ans
  main

------------------------------------------

{- Int input -}

parseInt :: BC.ByteString -> Int
parseInt = fst . fromJust . BC.readInt

parseInts :: BC.ByteString -> [Int]
parseInts = map parseInt <$> BC.words

readInt :: IO Int
readInt = parseInt <$> BC.getLine

readInts :: IO [Int]
readInts = parseInts <$> BC.getLine

{- Double Formatting -}

doubleFmt :: Double -> String
doubleFmt = Text.Printf.printf "%.12f"