import difflib

# Helper string for robust input reading in snippets
_PY_INPUT = """import sys
def input_gen():
    for line in sys.stdin:
        for t in line.split(): yield t
data = input_gen()
next_int = lambda: int(next(data))
next_str = lambda: next(data)
"""

_DOCS = {
    # ==============================================================================
    # 7.8 & 7.9 Series: TREES
    # ==============================================================================
    "tree traversals": {
        "baby": """from babygrad import scan, TreeOps\nn = scan.int()\nvals = []\nfor _ in range(n):\n    op = scan.int()\n    if op == 1: vals.append(scan.int())\n    else:\n        root = TreeOps.from_level_order(vals)\n        if not root: print("Empty")\n        else:\n            t = TreeOps.get_traversals(root)\n            print(*t['in'] if op==2 else (t['pre'] if op==3 else t['post']))""",
        "python": _PY_INPUT + """sys.setrecursionlimit(2000)\nclass Node:\n    def __init__(self, v): self.data, self.left, self.right = v, None, None\ndef insert_level(arr, i, n):\n    root = None\n    if i < n:\n        root = Node(arr[i])\n        root.left = insert_level(arr, 2*i + 1, n)\n        root.right = insert_level(arr, 2*i + 2, n)\n    return root\ndef get_trav(root):\n    res = {'in':[], 'pre':[], 'post':[]}\n    def dfs(n):\n        if not n: return\n        res['pre'].append(n.data)\n        dfs(n.left)\n        res['in'].append(n.data)\n        dfs(n.right)\n        res['post'].append(n.data)\n    dfs(root)\n    return res\n\nops = next_int()\nvals = []\nfor _ in range(ops):\n    op = next_int()\n    if op == 1: vals.append(next_int())\n    else:\n        if not vals: print("Empty"); continue\n        root = insert_level(vals, 0, len(vals))\n        t = get_trav(root)\n        print(*(t['in'] if op==2 else (t['pre'] if op==3 else t['post'])))"""
    },

    "bst ops": {
        "baby": """from babygrad import scan, TreeOps\nn, root = scan.int(), None\nres = []\nfor _ in range(n):\n    op = scan.int()\n    if op == 1: root = TreeOps.bst_insert(root, scan.int())\n    elif op == 2: root = TreeOps.bst_delete(root, scan.int())\n    elif op == 3: res.append("found" if TreeOps.bst_search(root, scan.int()) else "not found")\n    elif op in (4,5,6):\n        if not root: res.append("Empty")\n        else: res.append(" ".join(map(str, TreeOps.get_traversals(root)['in' if op==4 else ('pre' if op==5 else 'post')] )))\nprint(*res, sep='\\n')""",
        "python": _PY_INPUT + """class Node: \n    def __init__(self,d): self.data, self.left, self.right = d, None, None\ndef ins(r,v): \n    if not r: return Node(v)\n    if v<r.data: r.left=ins(r.left,v)\n    elif v>r.data: r.right=ins(r.right,v)\n    return r\ndef dele(r,v):\n    if not r: return r\n    if v<r.data: r.left=dele(r.left,v)\n    elif v>r.data: r.right=dele(r.right,v)\n    else:\n        if not r.left: return r.right\n        if not r.right: return r.left\n        t=r.right\n        while t.left: t=t.left\n        r.data=t.data\n        r.right=dele(r.right,t.data)\n    return r\ndef search(r,v):\n    if not r: return False\n    if r.data==v: return True\n    return search(r.left if v<r.data else r.right, v)\ndef trav(r, res):\n    if not r: return\n    res['pre'].append(r.data); trav(r.left,res); res['in'].append(r.data); trav(r.right,res); res['post'].append(r.data)\n\nn = next_int(); root = None; out = []\nfor _ in range(n):\n    op = next_int()\n    if op == 1: root = ins(root, next_int())\n    elif op == 2: root = dele(root, next_int())\n    elif op == 3: out.append("found" if search(root, next_int()) else "not found")\n    else:\n        if not root: out.append("Empty")\n        else:\n            d={'in':[],'pre':[],'post':[]}; trav(root,d)\n            k='in' if op==4 else ('pre' if op==5 else 'post')\n            out.append(" ".join(map(str, d[k])))\nprint("\\n".join(out))"""
    },

    "huffman": {
        "baby": """from babygrad import scan, TreeOps\nchars = scan.str()\nfreqs = scan.list_fixed(len(chars))\nroot = TreeOps.huffman_tree(chars, freqs)\ncodes = []\ndef dfs(n, p):\n    if not n: return\n    if n.data: codes.append(p)\n    dfs(n.left, p+"0"); dfs(n.right, p+"1")\ndfs(root, "")\nprint(*codes)""",
        "python": """import heapq\nclass N:\n    def __init__(s,f,c=None,o=0,l=None,r=None): s.f=f;s.c=c;s.o=o;s.l=l;s.r=r\n    def __lt__(s,o): return (s.f,s.o)<(o.f,o.o)\nchs=input().strip(); fs=list(map(int, input().split()))\npq=[N(f,c,i) for i,(c,f) in enumerate(zip(chs,fs))]\nheapq.heapify(pq); o=len(chs)\nwhile len(pq)>1:\n    a,b=heapq.heappop(pq),heapq.heappop(pq)\n    heapq.heappush(pq, N(a.f+b.f, None, o, a, b)); o+=1\nans=[]\ndef dfs(n,p):\n    if n.c!=None: ans.append(p)\n    else: dfs(n.l,p+"0"); dfs(n.r,p+"1")\ndfs(pq[0],""); print(" ".join(ans) + " ", end="")"""
    },

    "avl insert": {
        "baby": """from babygrad import scan, TreeOps\nvals = scan.list_fixed(scan.int())\nroot = None\nfor v in vals:\n    rot = []\n    root = TreeOps.avl_insert(root, v, lambda x: rot.append(x))\n    if rot: print(rot[-1])\n    print(*TreeOps.get_traversals(root)['in'])""",
        "python": _PY_INPUT + """class Node:\n    def __init__(self, d): self.data, self.left, self.right, self.h = d, None, None, 1\ndef ht(n): return n.h if n else 0\ndef bal(n): return ht(n.left) - ht(n.right) if n else 0\ndef rotr(y): \n    x=y.left; T=x.right; x.right=y; y.left=T\n    y.h=1+max(ht(y.left),ht(y.right)); x.h=1+max(ht(x.left),ht(x.right)); return x\ndef rotl(x):\n    y=x.right; T=y.left; y.left=x; x.right=T\n    x.h=1+max(ht(x.left),ht(x.right)); y.h=1+max(ht(y.left),ht(y.right)); return y\ndef ins(root, v, cb): \n    if not root: return Node(v)\n    if v < root.data: root.left = ins(root.left, v, cb)\n    elif v > root.data: root.right = ins(root.right, v, cb)\n    else: return root\n    root.h = 1 + max(ht(root.left), ht(root.right))\n    b = bal(root)\n    if b > 1 and v < root.left.data: cb("LL"); return rotr(root)\n    if b < -1 and v > root.right.data: cb("RR"); return rotl(root)\n    if b > 1 and v > root.left.data: cb("LR"); root.left = rotl(root.left); return rotr(root)\n    if b < -1 and v < root.right.data: cb("RL"); root.right = rotr(root.right); return rotl(root)\n    return root\ndef inorder(n, res): \n    if n: inorder(n.left, res); res.append(n.data); inorder(n.right, res)\n\nn = next_int()\nroot = None\nfor _ in range(n):\n    v = next_int(); rot = []\n    root = ins(root, v, lambda x: rot.append(x))\n    if rot: print(rot[-1])\n    res = []; inorder(root, res); print(*res)"""
    },

    "tree height": {
        "baby": """from babygrad import scan, TreeOps\nscan.int()\nprint(TreeOps.height(TreeOps.from_level_order(scan.list_until())))""",
        "python": _PY_INPUT + """n = next_str() # skip count\narr = []\ntry:\n    while True: arr.append(next_str())\nexcept: pass\nif not arr: print(0); exit()\ndef solve(idx):\n    if idx >= len(arr) or arr[idx] in ['null', 'n', '-1']: return 0\n    return 1 + max(solve(2*idx+1), solve(2*idx+2))\nprint(solve(0))"""
    },

    "build pre in": {
        "baby": """from babygrad import scan, TreeOps\nn = scan.int()\nprint(*TreeOps.get_traversals(TreeOps.build_pre_in(scan.list_fixed(n), scan.list_fixed(n)))['post'])""",
        "python": _PY_INPUT + """sys.setrecursionlimit(2000)\ndef build(pre, ino):\n    if not pre: return []\n    val = pre[0]; mid = ino.index(val)\n    left = build(pre[1:mid+1], ino[:mid])\n    right = build(pre[mid+1:], ino[mid+1:])\n    return left + right + [val]\nn = next_int()\nino = [next_int() for _ in range(n)]\npre = [next_int() for _ in range(n)]\nprint(*build(pre, ino))"""
    },

    "tree diameter": {
        "baby": """from babygrad import scan, TreeOps\nprint(TreeOps.diameter(TreeOps.from_level_order(scan.list_until(sentinel=None)), edges=True))""",
        "python": _PY_INPUT + """class Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\narr=[]\ntry:\n    while True: arr.append(next_str())\nexcept: pass\nif not arr: print(0); exit()\nnodes = [Node(int(x)) if x not in ['N','null'] else None for x in arr]\nroot = nodes[0]; q = [root]; i = 1\nwhile q and i<len(nodes):\n    c = q.pop(0)\n    if i<len(nodes) and nodes[i]: c.l=nodes[i]; q.append(c.l)\n    i+=1\n    if i<len(nodes) and nodes[i]: c.r=nodes[i]; q.append(c.r)\n    i+=1\nans = 0\ndef diam(n):\n    global ans\n    if not n: return 0\n    L, R = diam(n.l), diam(n.r)\n    ans = max(ans, L+R)\n    return 1 + max(L, R)\ndiam(root); print(ans)"""
    },

    "bst lca": {
        "baby": """from babygrad import scan, TreeOps\nn = scan.int()\nvals = scan.list_fixed(n)\nroot = None\nfor v in vals: root = TreeOps.bst_insert(root, v)\nprint(TreeOps.lca(root, scan.int(), scan.int()))""",
        "python": _PY_INPUT + """class Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\ndef ins(r,v):\n    if not r: return Node(v)\n    if v<r.d: r.l=ins(r.l,v)\n    elif v>r.d: r.r=ins(r.r,v)\n    return r\nn = next_int()\nvals = [next_int() for _ in range(n)]\nn1, n2 = next_int(), next_int()\nroot = None\nfor v in vals: root = ins(root, v)\ncurr = root\nwhile curr:\n    if curr.d > n1 and curr.d > n2: curr = curr.l\n    elif curr.d < n1 and curr.d < n2: curr = curr.r\n    else: print(curr.d); break"""
    },

    "perfect family": {
        "baby": """from babygrad import scan, TreeOps\nscan.int()\nroot = None\nfor v in scan.list_until(sentinel=None): root = TreeOps.bst_insert(root, int(v))\nprint(1 if TreeOps.perfect_family(root) else 0)""",
        "python": """n=int(input()); x=list(map(int,input().split()))\nif n<=2: print(1); exit()\nlast=x[-1]\nfor i in range(n-1):\n    if (x[i+1]-x[i])*(last-x[i])<=0: print(0); break\nelse: print(1)"""
    },

    "tree mirror": {
        "baby": """from babygrad import scan, TreeOps\nroot = TreeOps.from_level_order(scan.list_until('-1'))\nprint(1 if TreeOps.is_symmetric(root) else 0)""",
        "python": _PY_INPUT + """class Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\narr = []\ntry:\n    while True:\n        t = next_str()\n        if t == '-1': break\n        arr.append(t)\nexcept: pass\nnodes = [Node(int(x)) if x not in ['null','-1'] else None for x in arr]\nif not nodes: print(1); exit()\nroot = nodes[0]; q = [root]; i = 1\nwhile q and i<len(nodes):\n    c = q.pop(0)\n    if i<len(nodes) and nodes[i]: c.l=nodes[i]; q.append(c.l)\n    i+=1\n    if i<len(nodes) and nodes[i]: c.r=nodes[i]; q.append(c.r)\n    i+=1\ndef mir(a,b):\n    if not a and not b: return True\n    if not a or not b or a.d != b.d: return False\n    return mir(a.l, b.r) and mir(a.r, b.l)\nprint(1 if mir(root.l, root.r) else 0)"""
    },

    "kth smallest": {
        "baby": """from babygrad import scan, TreeOps\nvals = scan.list_until('-1')\nprint(TreeOps.kth_smallest(TreeOps.from_level_order(vals), scan.int()))""",
        "python": _PY_INPUT + """arr = []\nwhile True: \n    t = next_str()\n    if t == '-1': break\n    arr.append(t)\nk = next_int()\nclass Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\nnodes = [Node(int(x)) if x!='null' else None for x in arr]\nif not nodes: print(0); exit()\nroot = nodes[0]; q = [root]; i = 1\nwhile q and i<len(nodes):\n    c = q.pop(0)\n    if i<len(nodes) and nodes[i]: c.l=nodes[i]; q.append(c.l)\n    i+=1\n    if i<len(nodes) and nodes[i]: c.r=nodes[i]; q.append(c.r)\n    i+=1\nstack, curr, cnt = [], root, 0\nwhile stack or curr:\n    while curr: stack.append(curr); curr=curr.l\n    curr = stack.pop(); cnt+=1\n    if cnt==k: print(curr.d); exit()\n    curr = curr.r"""
    },

    "level order": {
        "baby": """from babygrad import scan, TreeOps\nscan.int()\nroot = None\nfor v in scan.list_until(sentinel=None): root = TreeOps.bst_insert(root, int(v))\nprint(*TreeOps.bfs_list(root))""",
        "python": _PY_INPUT + """class Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\ndef ins(r,v):\n    if not r: return Node(v)\n    if v<r.d: r.l=ins(r.l,v)\n    elif v>r.d: r.r=ins(r.r,v)\n    return r\nn = next_int(); root = None\nfor _ in range(n): root = ins(root, next_int())\nq, res = [root], []\nwhile q:\n    c = q.pop(0)\n    if c: res.append(c.d); q.append(c.l); q.append(c.r)\nprint(*res)"""
    },

    "max leaf sum": {
        "baby": """from babygrad import scan, TreeOps\nprint(TreeOps.max_leaf_to_leaf_sum(TreeOps.from_level_order(scan.list_until('-1'))))""",
        "python": _PY_INPUT + """arr = []\ntry:\n    while True:\n        t = next_str()\n        if t == '-1': break\n        arr.append(t)\nexcept: pass\nclass Node: \n    def __init__(self,d): self.d,self.l,self.r=d,None,None\nnodes = [Node(int(x)) if x not in ['null','-1'] else None for x in arr]\nif not nodes or not nodes[0]: print(0); exit()\nroot = nodes[0]; q = [root]; i = 1\nwhile q and i<len(nodes):\n    c = q.pop(0)\n    if i<len(nodes) and nodes[i]: c.l=nodes[i]; q.append(c.l)\n    i+=1\n    if i<len(nodes) and nodes[i]: c.r=nodes[i]; q.append(c.r)\n    i+=1\nans = -float('inf')\ndef solve(n):\n    global ans\n    if not n: return -float('inf')\n    if not n.l and not n.r: return n.d\n    l, r = solve(n.l), solve(n.r)\n    if n.l and n.r: ans = max(ans, l+r+n.d); return max(l,r)+n.d\n    return (l if n.l else r) + n.d\nsolve(root); print(ans)"""
    },

    # ==============================================================================
    # GRAPHS
    # ==============================================================================

    "graph matrix ops": {
        "baby": """from babygrad import scan, GraphOps\nops = scan.int()\ng = GraphOps()\nverts = set()\nfor _ in range(ops):\n    cmd = scan.int()\n    if cmd == 1: verts.add(scan.int())\n    elif cmd == 2: \n        v = scan.int()\n        if v in verts: \n            verts.remove(v)\n            if v in g.g: g.g.remove_node(v)\n    elif cmd == 3: g.add(scan.int(), scan.int())\n    elif cmd == 4: \n        u, v = scan.int(), scan.int()\n        if g.g.has_edge(u, v): g.g.remove_edge(u, v)\n    elif cmd == 5: \n        print("Yes" if g.g.has_edge(scan.int(), scan.int()) else "No")\n\ns_verts = sorted(list(verts))\nfor i in s_verts: print(*[1 if g.g.has_edge(i, j) else 0 for j in s_verts])""",
        "python": """n=int(input()); ops=[input().split() for _ in range(n)]\nverts=set(); edges={}\nfor op in ops:\n    if op[0]=='1': verts.add(int(op[1]))\n    elif op[0]=='2':\n        x=int(op[1])\n        if x in verts: verts.remove(x); keys=[k for k in edges if x in k]; [edges.pop(k) for k in keys]\n    elif op[0]=='3': \n        u,v=int(op[1]),int(op[2]); edges[tuple(sorted((u,v)))]=1\n    elif op[0]=='4':\n        u,v=int(op[1]),int(op[2]); k=tuple(sorted((u,v))); edges.pop(k, None)\n    elif op[0]=='5':\n        u,v=int(op[1]),int(op[2]); print("Yes" if tuple(sorted((u,v))) in edges else "No")\nsv=sorted(verts)\nfor u in sv: print(*(1 if tuple(sorted((u,v))) in edges else 0 for v in sv))"""
    },

    "graph adj list": {
        "baby": """from babygrad import scan, GraphOps\nn, ops = scan.int(), scan.int()\ng = GraphOps()\nfor _ in range(ops):\n    cmd = scan.str()\n    if cmd == 'ADD': g.add(scan.int(), scan.int())\n    elif cmd == 'DEL': \n        u, v = scan.int(), scan.int()\n        if g.g.has_edge(u, v): g.g.remove_edge(u, v)\n    elif cmd == 'NEIGHBORS':\n        u = scan.int()\n        nbrs = sorted(list(g.g.neighbors(u))) if u in g.g else []\n        print(*(nbrs if nbrs else [-1]))\ng.print_adj_list(n)""",
        "python": _PY_INPUT + """from collections import defaultdict\nn, ops = next_int(), next_int()\nadj = defaultdict(set)\nfor _ in range(ops):\n    cmd = next_str()\n    if cmd == 'ADD':\n        u, v = next_int(), next_int(); adj[u].add(v); adj[v].add(u)\n    elif cmd == 'DEL':\n        u, v = next_int(), next_int()\n        if v in adj[u]: adj[u].remove(v)\n        if u in adj[v]: adj[v].remove(u)\n    elif cmd == 'NEIGHBORS':\n        u = next_int(); res = sorted(list(adj[u]))\n        print(*(res if res else [-1]))\nfor i in range(n):\n    print(f"{i}:{' '.join(map(str, sorted(list(adj[i]))))} " if adj[i] else f"{i}:")"""
    },

    "dfs traversal": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps()\nfor _ in range(e): g.add(scan.int(), scan.int())\nprint(*g.dfs(scan.int()))""",
        "python": """def dfs(m,v,s): v[s]=True; print(s, end=" "); [dfs(m,v,i) for i in range(len(m)) if m[s][i] and not v[i]]\nn=int(input()); e=int(input()); m=[[0]*n for _ in range(n)]\nfor _ in range(e): a,b=map(int,input().split()); m[a][b]=m[b][a]=1\ns=int(input()); dfs(m,[False]*n,s)"""
    },

    "bfs traversal": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps()\nfor _ in range(e): g.add(scan.int(), scan.int())\nres = g.bfs(scan.int())\nq = [res[0]]; vis = {res[0]}\nwhile q:\n    print(*q)\n    nq = []\n    for u in q:\n        for v in sorted(g.g.neighbors(u)): \n            if v not in vis: vis.add(v); nq.append(v)\n    q = nq""",
        "python": """from collections import deque\nn=int(input()); e=int(input()); m=[[0]*n for _ in range(n)]\nfor _ in range(e): a,b=map(int,input().split()); m[a][b]=m[b][a]=1\ns=int(input()); q=deque([s]); v=[False]*n; v[s]=True\nwhile q:\n    lvl=[]\n    for _ in range(len(q)):\n        node=q.popleft(); lvl.append(node)\n        for i in range(n):\n            if m[node][i] and not v[i]: v[i]=True; q.append(i)\n    print(*lvl, end=" "); print()"""
    },

    "connected components": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps()\ng.g.add_nodes_from(range(v))\nfor _ in range(e): g.add(scan.int(), scan.int())\nfor c in g.components(): print(*c)""",
        "python": _PY_INPUT + """from collections import defaultdict\nv, e = next_int(), next_int()\nadj = defaultdict(list)\nfor _ in range(e):\n    u, w = next_int(), next_int(); adj[u].append(w); adj[w].append(u)\nvis = set(); comps = []\nfor i in range(v):\n    if i not in vis:\n        q = [i]; vis.add(i); comp = []\n        while q:\n            u = q.pop(0); comp.append(u)\n            for nbr in adj[u]:\n                if nbr not in vis: vis.add(nbr); q.append(nbr)\n        comps.append(sorted(comp))\nfor c in sorted(comps, key=lambda x: x[0]): print(*c)"""
    },

    "topo kahn": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\ng.g.add_nodes_from(range(v))\nfor _ in range(e): g.add(scan.int(), scan.int())\nt = g.topo_sort()\nprint(*t if t else ["Cycle detected"])""",
        "python": """import heapq\nn,e=map(int,input().split()); adj=[[] for _ in range(n)]; ind=[0]*n\nfor _ in range(e): u,v=map(int,input().split()); adj[u].append(v); ind[v]+=1\npq=[i for i in range(n) if ind[i]==0]; heapq.heapify(pq); topo=[]\nwhile pq:\n    u=heapq.heappop(pq); topo.append(u)\n    for v in adj[u]:\n        ind[v]-=1\n        if ind[v]==0: heapq.heappush(pq,v)\nprint(*topo, end=" ") if len(topo)==n else print("Cycle detected"); print()"""
    },

    "topo matrix": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\nmat = scan.matrix(n, n)\ng = GraphOps.from_matrix(mat, directed=True)\nt = g.topo_sort()\nprint(*t)""",
        "python": _PY_INPUT + """import heapq\nn = next_int()\nindeg = {i:0 for i in range(n)}; adj = {i:[] for i in range(n)}\nfor r in range(n):\n    for c in range(n):\n        if next_int() == 1: adj[r].append(c); indeg[c] += 1\npq = [i for i in range(n) if indeg[i]==0]; heapq.heapify(pq)\nres = []\nwhile pq:\n    u = heapq.heappop(pq); res.append(u)\n    for v in adj[u]:\n        indeg[v] -= 1\n        if indeg[v] == 0: heapq.heappush(pq, v)\nprint(*res)"""
    },

    "is bipartite": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\nmat = scan.matrix(n, n)\ng = GraphOps.from_matrix(mat)\nscan.int() # source ignored\nprint("Yes" if g.is_bipartite() else "No")""",
        "python": _PY_INPUT + """n = next_int()\nadj = {i:[] for i in range(n)}\nfor r in range(n):\n    for c in range(n): \n        if next_int(): adj[r].append(c)\nnext_str() # skip source\ncolor = {}; possible = True\nfor i in range(n):\n    if i not in color:\n        color[i] = 0; q = [i]\n        while q:\n            u = q.pop(0)\n            for v in adj[u]:\n                if v not in color: color[v] = 1 - color[u]; q.append(v)\n                elif color[v] == color[u]: possible = False\nprint("Yes" if possible else "No")"""
    },

    "count islands": {
        "baby": """from babygrad import scan, GraphOps\nr, c = scan.int(), scan.int()\ngrid = scan.matrix(r, c)\nprint(GraphOps.count_islands(grid))""",
        "python": """def cnt(g,r,c):\n    vis=[[0]*c for _ in range(r)]; d=[(1,0),(-1,0),(0,1),(0,-1)]\n    def dfs(i,j): \n        vis[i][j]=1\n        for dr,dc in d: \n            nx,ny=i+dr,j+dc\n            if 0<=nx<r and 0<=ny<c and g[nx][ny] and not vis[nx][ny]: dfs(nx,ny)\n    isl=0\n    for i in range(r):\n        for j in range(c):\n            if g[i][j] and not vis[i][j]: isl+=1; dfs(i,j)\n    return isl\nn=int(input()); m=int(input()); g=[list(map(int,input().split())) for _ in range(n)]; print(cnt(g,n,m))"""
    },

    "min network ops": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\nconns = []\nwhile True: \n    u = scan.int()\n    if u == -1: break\n    conns.append((u, scan.int()))\nif len(conns) < n - 1: print(-1)\nelse:\n    g = GraphOps()\n    g.g.add_nodes_from(range(n))\n    g.g.add_edges_from(conns)\n    print(len(g.components()) - 1)""",
        "python": _PY_INPUT + """n = next_int(); edges = []\nwhile True:\n    try:\n        u = next_int()\n        if u == -1: break\n        edges.append((u, next_int()))\n    except: break\nif len(edges) < n-1: print(-1)\nelse:\n    p = list(range(n))\n    def find(x): \n        if p[x]!=x: p[x]=find(p[x])\n        return p[x]\n    def union(a,b): p[find(a)] = find(b)\n    for u,v in edges: union(u,v)\n    print(len(set(find(i) for i in range(n))) - 1)"""
    },

    "job scheduling": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\ng.g.add_nodes_from(range(1, v+1))\nfor _ in range(e): g.add(scan.int(), scan.int())\ntimes = {n: 1 for n in range(1, v+1)}\nfor u in g.topo_sort():\n    for v in g.g.neighbors(u):\n        times[v] = max(times[v], times[u] + 1)\nprint(*[times[i] for i in range(1, v+1)])""",
        "python": """import heapq\ndef job(ops):\n    hp=[]; cnt=0; out=[]\n    for op in ops:\n        p=op.split()\n        if p[0]=="ADD": heapq.heappush(hp,(-int(p[1]),cnt,p[2])); cnt+=1\n        elif p[0]=="EXECUTE": out.append(f"Executed: {heapq.heappop(hp)[2]}" if hp else "No jobs to execute")\n    return out\n# Logic placeholder as problem 15.5.5 input differs from 11.8.2"""
    },

    "job priority": {
        "python": """import heapq\nhp=[]; cnt=0\n# Usage depends on input loop\n# For generic op list:\n# heapq.heappush(hp, (-prio, cnt, name)); cnt+=1\n# heapq.heappop(hp)"""
    },

    "prerequisites": {
        "baby": """from babygrad import scan, GraphOps\nn, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\nfor _ in range(e): g.add(scan.int(), scan.int())\nprint(1 if g.topo_sort() else 0)""",
        "python": _PY_INPUT + """from collections import defaultdict\nn, e = next_int(), next_int()\nadj = defaultdict(list); indeg = {i:0 for i in range(n)}\nfor _ in range(e):\n    u,v = next_int(), next_int(); adj[u].append(v); indeg[v]+=1\nq = [i for i in range(n) if indeg[i]==0]; cnt=0\nwhile q:\n    u=q.pop(0); cnt+=1\n    for v in adj[u]:\n        indeg[v]-=1\n        if indeg[v]==0: q.append(v)\nprint(1 if cnt==n else 0)"""
    },

    "flood fill": {
        "baby": """from babygrad import scan, GraphOps\nr, c = scan.int(), scan.int()\ngrid = scan.matrix(r, c)\nx, y, col = scan.int(), scan.int(), scan.int()\nres = GraphOps.flood_fill(grid, x, y, col)\nfor row in res: print(*row)""",
        "python": """from collections import deque\nn,m=map(int,input().split()); img=[list(map(int,input().split())) for _ in range(n)]\nr,c,nc=map(int,input().split()); oc=img[r][c]\nif oc!=nc:\n    q=deque([(r,c)]); img[r][c]=nc\n    while q:\n        x,y=q.popleft()\n        for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:\n            nx,ny=x+dx,y+dy\n            if 0<=nx<n and 0<=ny<m and img[nx][ny]==oc: img[nx][ny]=nc; q.append((nx,ny))\nfor row in img: print(*row, end=" "); print()"""
    },

    "nasa pairs": {
        "baby": """from babygrad import scan, GraphOps\nn, p = scan.int(), scan.int()\ng = GraphOps()\ng.g.add_nodes_from(range(n))\nfor _ in range(p): g.add(scan.int(), scan.int())\nsizes = [len(c) for c in g.components()]\nrem = sum(sizes); ans = 0\nfor s in sizes: rem -= s; ans += s * rem\nprint(ans)""",
        "python": _PY_INPUT + """n, p = next_int(), next_int()\nparent = list(range(n))\ndef find(x): \n    if parent[x]!=x: parent[x]=find(parent[x])\n    return parent[x]\ndef union(a,b): parent[find(a)] = find(b)\nfor _ in range(p): union(next_int(), next_int())\ncounts = {}; \nfor i in range(n): r = find(i); counts[r] = counts.get(r, 0) + 1\nsizes = list(counts.values())\nans = 0; rem = n\nfor s in sizes: rem -= s; ans += s * rem\nprint(ans)"""
    },

    "create graph": {
        "baby": """from babygrad import scan, GraphOps\nv = scan.int()\nif not (1 <= v <= 10): print("-1")\nelse:\n    mat = scan.matrix(v, v, transformer=lambda x: int(x))\n    for row in mat: print(*row)""",
        "python": _PY_INPUT + """v = next_int()\nif not (1 <= v <= 10): print("-1")\nelse:\n    for _ in range(v):\n        print(*[next_str() for _ in range(v)])"""
    },

    "dfs reachable": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\nmat = scan.matrix(n, n)\ng = GraphOps.from_matrix(mat, directed=True)\nstart = scan.int()\nprint(f"Reachable nodes from {start}:", *g.dfs(start))""",
        "python": _PY_INPUT + """from collections import defaultdict\nn = next_int(); adj=defaultdict(list)\nfor r in range(n):\n    for c in range(n):\n        if next_str()=='1': adj[r].append(c)\nstart = next_int()\nvis = set(); res = []; stack=[start]\nwhile stack:\n    u = stack.pop()\n    if u not in vis:\n        vis.add(u); res.append(u)\n        for v in sorted(adj[u], reverse=True): \n            if v not in vis: stack.append(v)\nprint(f"Reachable nodes from {start}:", *res)"""
    },

    "dfs adj list": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\nfor _ in range(e): g.add(scan.int(), scan.int())\nprint(*g.dfs(scan.int()))""",
        "python": _PY_INPUT + """from collections import defaultdict\nv, e = next_int(), next_int()\nadj = defaultdict(list)\nfor _ in range(e): \n    u, w = next_int(), next_int()\n    adj[u].append(w); adj[w].append(u)\nstart=next_int(); stack=[start]; vis=set(); res=[]\nwhile stack:\n    u=stack.pop()\n    if u not in vis:\n        vis.add(u); res.append(u)\n        # Stack logic: push Descending to pop Ascending\n        for v in sorted(adj[u], reverse=True):\n            if v not in vis: stack.append(v)\nprint(*res)"""
    },

    "is connected": {
        "baby": """from babygrad import scan, GraphOps\nv = scan.int()\nmat = scan.matrix(v, v)\ng = GraphOps.from_matrix(mat)\nu, v = scan.int(), scan.int()\nprint(nx.has_path(g.g, u, v))""",
        "python": _PY_INPUT + """v=next_int(); adj={i:[] for i in range(v)}\nfor r in range(v):\n    for c in range(v):\n        if next_str()=='1': adj[r].append(c)\ns, d = next_int(), next_int()\nq=[s]; vis={s}\nfound=False\nwhile q:\n    u=q.pop(0)\n    if u==d: found=True; break\n    for nbr in adj[u]:\n        if nbr not in vis: vis.add(nbr); q.append(nbr)\nprint(found)"""
    },

    "biconnected": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps()\nfor _ in range(e): g.add(scan.int(), scan.int())\nprint(g.biconnected_count())""",
        "python": _PY_INPUT + """sys.setrecursionlimit(2000)\nv, e = next_int(), next_int()\nadj={i:[] for i in range(v)}\nfor _ in range(e): \n    try: u, w = next_int(), next_int(); adj[u].append(w); adj[w].append(u)\n    except: break\ntime=0; disc=[-1]*v; low=[-1]*v; stack=[]; count=0\ndef dfs(u, p=-1):\n    global time, count\n    disc[u]=low[u]=time; time+=1; children=0\n    for v in adj[u]:\n        if v==p: continue\n        if disc[v]!=-1: low[u]=min(low[u], disc[v]); stack.append((u,v))\n        else:\n            stack.append((u,v)); children+=1; dfs(v, u); low[u]=min(low[u], low[v])\n            if (p!=-1 and low[v]>=disc[u]) or (p==-1 and children>1):\n                count+=1\n                while stack[-1]!=(u,v): stack.pop()\n                stack.pop()\n    return\nfor i in range(v): \n    if disc[i]==-1: \n        dfs(i); \n        if stack: count+=1; stack=[]\nprint(count)"""
    },

    "cycle detect": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps()\nfor _ in range(e): g.add(scan.int(), scan.int())\ntry: \n    nx.find_cycle(g.g)\n    print("Yes")\nexcept: print("No")""",
        "python": """def f(p,x): return p[x] if p[x]==x else f(p,p[x])\ndef u(p,r,x,y): \n    rx,ry=f(p,x),f(p,y)\n    if rx==ry: return 0\n    if r[rx]<r[ry]: p[rx]=ry\n    elif r[rx]>r[ry]: p[ry]=rx\n    else: p[ry]=rx; r[rx]+=1\n    return 1\nn=int(input().strip()); adj=[list(map(int,input().split())) for _ in range(n)]\np=[i for i in range(n)]; r=[0]*n; cyc=0\nfor i in range(n):\n    for j in range(i+1,n):\n        if adj[i][j] and not u(p,r,i,j): cyc=1; break\n    if cyc: break\nprint("Cycle detected" if cyc else "No cycle detected")"""
    },

    "all paths": {
        "baby": """from babygrad import scan, GraphOps\nv, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\nfor _ in range(e): g.add(scan.int(), scan.int())\nsrc, dst = scan.int(), scan.int()\npaths = g.all_paths(src, dst)\nfor p in paths: print(*p)""",
        "python": _PY_INPUT + """v, e = next_int(), next_int(); adj={i:[] for i in range(v)}\nfor _ in range(e): u,w=next_int(),next_int(); adj[u].append(w)\nsrc, dst = next_int(), next_int()\ndef dfs(u, path):\n    if u==dst: print(*path); return\n    for nbr in sorted(adj[u]):\n        if nbr not in path: dfs(nbr, path+[nbr])\ndfs(src, [src])"""
    },

    "graph symmetric": {
        "baby": """from babygrad import scan, GraphOps\nv = scan.int()\nmat = scan.matrix(v, v)\nprint("The graph is symmetric" if GraphOps.is_symmetric(mat) else "The graph is not symmetric")""",
        "python": _PY_INPUT + """v=next_int(); mat=[[next_str() for _ in range(v)] for _ in range(v)]\nsym=True\nfor r in range(v):\n    for c in range(v):\n        if mat[r][c] != mat[c][r]: sym=False; break\nprint("The graph is symmetric" if sym else "The graph is not symmetric")"""
    },

    "mother vertex": {
        "baby": """from babygrad import scan, GraphOps\nn, e = scan.int(), scan.int()\ng = GraphOps(directed=True)\ng.g.add_nodes_from(range(n))\nfor _ in range(e): g.add(scan.int(), scan.int())\nprint(g.mother_vertex(n))""",
        "python": _PY_INPUT + """sys.setrecursionlimit(5000)\nn, e = next_int(), next_int(); adj={i:[] for i in range(n)}\nfor _ in range(e): u,w=next_int(),next_int(); adj[u].append(w)\nvis=set(); last=0\ndef dfs(u): \n    vis.add(u)\n    for v in adj[u]: \n        if v not in vis: dfs(v)\nfor i in range(n): \n    if i not in vis: dfs(i); last=i\nvis=set(); dfs(last)\nprint(last if len(vis)==n else -1)"""
    },

    "path exists": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\ne = scan.int()\ng = GraphOps()\nfor _ in range(e): g.add(scan.int(), scan.int())\nsrc, dst = scan.int(), scan.int()\nprint("true" if nx.has_path(g.g, src, dst) else "false")""",
        "python": _PY_INPUT + """n, e = next_int(), next_int(); adj={i:[] for i in range(n)}\nfor _ in range(e): u,w=next_int(),next_int(); adj[u].append(w); adj[w].append(u)\ns, t = next_int(), next_int()\nq=[s]; vis={s}; found=False\nwhile q:\n    u=q.pop(0)\n    if u==t: found=True; break\n    for v in adj[u]:\n        if v not in vis: vis.add(v); q.append(v)\nprint("true" if found else "false")"""
    },

    "grid path 123": {
        "baby": """from babygrad import scan, GraphOps\nn = scan.int()\ngrid = scan.matrix(n, n)\nprint(1 if GraphOps.grid_path(grid, 1, 2, {3}) else 0)""",
        "python": _PY_INPUT + """n = next_int(); grid=[]; start=None\nfor r in range(n): \n    row=[next_int() for _ in range(n)]; grid.append(row)\n    if 1 in row: start=(r, row.index(1))\nq=[start]; vis={start}; found=False\nwhile q:\n    r,c=q.pop(0)\n    if grid[r][c]==2: found=True; break\n    for dr,dc in [(0,1),(0,-1),(1,0),(-1,0)]:\n        nr,nc=r+dr,c+dc\n        if 0<=nr<n and 0<=nc<n and (nr,nc) not in vis and grid[nr][nc] in [2,3]:\n            vis.add((nr,nc)); q.append((nr,nc))\nprint(1 if found else 0)"""
    },

    "transpose matrix": {
        "baby": """from babygrad import scan, GraphOps\nv = scan.int()\nmat = scan.matrix(v, v)\nres = GraphOps.transpose_matrix(mat)\nfor row in res: print(*row)""",
        "python": _PY_INPUT + """v = next_int(); mat=[[next_str() for _ in range(v)] for _ in range(v)]\nt = [[mat[j][i] for j in range(v)] for i in range(v)]\nfor row in t: print(*row)"""
    },

    "island strike": {
        "baby": """from babygrad import scan, GraphOps\nn, m = scan.int(), scan.int()\ngrid = [list(scan.str()) for _ in range(n)]\nprint(GraphOps.count_islands(grid))""",
        "python": _PY_INPUT + """sys.setrecursionlimit(5000)\nn, m = next_int(), next_int()\ngrid=[list(next_str()) for _ in range(n)]\nvis=set(); cnt=0\ndef dfs(x,y):\n    if not (0<=x<n and 0<=y<m) or (x,y) in vis or grid[x][y]=='0': return\n    vis.add((x,y))\n    for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]: dfs(x+dx, y+dy)\nfor i in range(n):\n    for j in range(m):\n        if grid[i][j]=='1' and (i,j) not in vis: dfs(i,j); cnt+=1\nprint(cnt)"""
    },

    "degrees": {
        "baby": """from babygrad import scan, GraphOps\nv = scan.int()\ne = scan.int()\ng = GraphOps(directed=True)\ng.g.add_nodes_from(range(v))\nfor _ in range(e): g.add(scan.int(), scan.int())\ng.print_degrees(v)""",
        "python": _PY_INPUT + """v, e = next_int(), next_int()\nind={i:0 for i in range(v)}; outd={i:0 for i in range(v)}\nfor _ in range(e):\n    u, w = next_int(), next_int()\n    outd[u]+=1; ind[w]+=1\nfor i in range(v): print(f"Vertex {i}: In-degree = {ind[i]}, Out-degree = {outd[i]}")"""
    },

    # ==============================================================================
    # ALGO & MISC
    # ==============================================================================

    "merge sort": {
        "python": """r=0; c=0\ndef m(a,s,mid,e):\n global c; t=[]; i,j=s,mid+1\n while i<=mid and j<=e: c+=1; t.append(a[i] if a[i]<=a[j] else a[j]); i+=(1 if t[-1]==a[i] else 0); j+=(1 if t[-1]!=a[i-1] else 0)\n while i<=mid: t.append(a[i]); i+=1\n while j<=e: t.append(a[j]); j+=1\n for k in range(len(t)): a[s+k]=t[k]\ndef ms(a,s,e):\n global r; r+=1\n if s>=e: return\n mid=(s+e)//2; ms(a,s,mid); ms(a,mid+1,e); m(a,s,mid,e)\nn=int(input()); a=list(map(int,input().split())); ms(a,0,n-1); print(*a, end=" "); print(); print(r); print(c)"""
    },

    "quick sort": {
        "python": """c=0; r=0\ndef p(a,l,h):\n global c; piv=a[h]; i=l-1\n for j in range(l,h): c+=1; (i:=i+1, a.__setitem__(i, a[j]), a.__setitem__(j, a[i])) if a[j]<piv else None\n a[i+1],a[h]=a[h],a[i+1]; return i+1\ndef qs(a,l,h):\n global r; \n if l<h: r+=1; pi=p(a,l,h); qs(a,l,pi-1); qs(a,pi+1,h)\nn=int(input()); a=list(map(int,input().split())); qs(a,0,n-1); print(*a, end=" "); print(); print(c); print(r)"""
    },

    "merge arrays": {
        "python": """l1=list(map(int,input().split())); m=int(input())\nl2=list(map(int,input().split())); n=int(input())\nprint(sorted(l1[:m]+l2[:n]))"""
    },

    "sort bit count": {
        "python": """n=int(input()); a=list(map(int,input().split())); a.sort(key=lambda x:-x.bit_count()); print("["+", ".join(map(str,a))+"]")"""
    },

    "distinct windows": {
        "python": """n=int(input()); a=list(map(int,input().split())); k=int(input())\nf={}; d=0\nfor i in range(k): \n if f.get(a[i],0)==0: d+=1\n f[a[i]]=f.get(a[i],0)+1\nprint(d)\nfor i in range(k,n):\n o=a[i-k]; f[o]-=1\n if f[o]==0: d-=1\n if f.get(a[i],0)==0: d+=1\n f[a[i]]=f.get(a[i],0)+1; print(d)"""
    },

    "group anagrams": {
        "python": """n=int(input()); w=input().split(); g={}\nfor s in w:\n k=''.join(sorted(s))\n if k not in g: g[k]=[]\n g[k].append(s)\nr=list(g.values()); r.sort(key=lambda x:x[0])\nfor x in r: print(" ".join(x), end=" "); print()"""
    },

    "least k elements": {
        "python": """n=int(input()); a=list(map(int,input().split())); k=int(input())\nt=[x for x in a if a.count(x)==1]; t.sort()\nprint("[" + ", ".join(map(str, t[-1:-k-1:-1])) + "]", end="")"""
    },

    "quadratic probing": {
        "python": """n,m=map(int,input().split())\nif n==0: print("Hash Table is empty"); exit()\nk=list(map(int,input().split())); h=[-1]*m\nfor x in k:\n idx=x%m\n if h[idx]==-1: h[idx]=x\n else:\n  ins=0\n  for i in range(1,m):\n   ni=(idx+i*i)%m\n   if h[ni]==-1: h[ni]=x; ins=1; break\n  if not ins: print(f"Hash table is full. Cannot insert records from key {x}"); break\nfor i in range(m): print(f"T[{i}] -> {h[i]}")"""
    },

    "linear probing": {
        "python": """n,m=map(int,input().split())\nif n==0: print("Hash Table is empty"); exit()\nk=list(map(int,input().split())); h=[-1]*m\nfor x in k:\n idx=x%m\n if h[idx]==-1: h[idx]=x\n else:\n  ins=0\n  for i in range(1,m):\n   ni=(idx+i)%m\n   if h[ni]==-1: h[ni]=x; ins=1; break\n  if not ins: print(f"Hash table is full. Cannot insert records from key {x}"); break\nfor i in range(m): print(f"T[{i}] -> {h[i]}")"""
    },
    
    "bst to minheap": {
        "python": """from collections import deque\nclass N: \n def __init__(s,v): s.d=v; s.l=None; s.r=None\ndef b(l): \n if not l or l[0]==-1: return None\n r=N(l[0]); q=deque([r]); i=1\n while q and i<len(l):\n  n=q.popleft()\n  if i<len(l) and l[i]!=-1: n.l=N(l[i]); q.append(n.l)\n  i+=1\n  if i<len(l) and l[i]!=-1: n.r=N(l[i]); q.append(n.r)\n  i+=1\n return r\ndef io(r,res): \n if r: io(r.l,res); res.append(r.d); io(r.r,res)\ndef pre(r,s,idx): \n if not r: return idx\n r.d=s[idx]; idx+=1; idx=pre(r.l,s,idx); idx=pre(r.r,s,idx); return idx\ndef pp(r): \n if r: print(r.d, end=' '); pp(r.l); pp(r.r)\nl=list(map(int,input().split())); r=b(l); s=[]; io(r,s); pre(r,s,0); pp(r)"""
    }
}

def doc(key: str, language="baby"):
    """
    Prints solution code.
    Args:
        key: The problem key (e.g., 'huffman', 'flood fill').
        language: 'baby' for babygrad library code, 'python' for pure standard python.
    """
    if not key: return
    
    # Normalize key (strip spaces, lowercase)
    k = key.lower().strip()
    
    # Fuzzy matching helper
    matches = difflib.get_close_matches(k, _DOCS.keys(), n=1, cutoff=0.6)
    
    if k in _DOCS:
        print(_DOCS[k].get(language, "# Language not found"))
    elif matches:
        # If user made a typo (e.g. "flood filll"), suggest the closest match
        print(f"# Did you mean '{matches[0]}'?\n")
        print(_DOCS[matches[0]].get(language, "# Language not found"))
    else:
        # Sort keys for readable error message
        print(f"# No docs found for '{key}'. Available:\n# " + "\n# ".join(sorted(_DOCS.keys())))