"""Bor od žaruljica - tester.

Kontestis: stdin = sep, input, expected, output, sep -> prints custom:partial:<p> or wa.
Local:     python3 tester.py input.txt answer.txt [-v] -> prints score (2 decimals) or INVALID + exit 1.

S = 2*Ew + C (Ew = weighted wrong bulbs, C = cost of pressed switches), W = sum of all bulb weights.
q = max(0, W - S) / W rounded to 6 decimals, points = 1 + 99999*q.
"""
import sys


def parse_input(text):
    lines = text.strip().split("\n")
    n, k = map(int, lines[0].split())
    target = "".join(lines[1 + r].strip() for r in range(n))
    weight = [int(ch) for r in range(n) for ch in lines[1 + n + r].strip()]
    if len(target) != n * n or len(weight) != n * n:
        raise ValueError("bad input grid")
    cost, sw = [], []
    for j in range(k):
        toks = lines[1 + 2 * n + j].split()
        cost.append(int(toks[0]))
        cells = []
        for tok in toks[1:]:
            r, c = tok.split(",")
            cells.append((int(r) - 1) * n + int(c) - 1)
        sw.append(cells)
    return n, k, target, weight, cost, sw


def evaluate(n, k, target, weight, cost, sw, ans):
    """Returns (points, S, Ew, C, W) or raises ValueError."""
    s = ans.strip()
    if len(s) != k:
        raise ValueError(f"expected {k} characters, got {len(s)}")
    if set(s) - {"0", "1"}:
        raise ValueError("answer may contain only characters 0 and 1")
    light = bytearray(n * n)
    c_sum = 0
    for j, ch in enumerate(s):
        if ch == "1":
            c_sum += cost[j]
            for p in sw[j]:
                light[p] ^= 1
    ew = 0
    for p, t in enumerate(target):
        if light[p] != (t == "1"):
            ew += weight[p]
    S = 2 * ew + c_sum
    W = sum(weight)
    num = max(0, W - S) * 1000000
    q6 = (2 * num + W) // (2 * W)  # round half up to 6 decimals, integer millionths
    points = (1000000 + 99999 * q6) / 1000000
    return points, S, ew, c_sum, W, 1000000 + 99999 * q6


def main():
    if len(sys.argv) >= 3:
        with open(sys.argv[1]) as f:
            inp = parse_input(f.read())
        with open(sys.argv[2], encoding="utf-8", errors="replace") as f:
            ans = f.read()
        try:
            points, S, ew, c, W, _ = evaluate(*inp, ans)
        except ValueError as ex:
            print(f"INVALID: {ex}")
            sys.exit(1)
        if "-v" in sys.argv:
            print(f"S={S} Ew={ew} C={c} W={W}", file=sys.stderr)
        print(f"{points:.2f}")
        return
    data = sys.stdin.read()
    sep = data.split("\n", 1)[0] + "\n"
    try:
        _, inp, _expected, output, _ = data.split(sep)
        micro = evaluate(*parse_input(inp), output)[5]  # points in millionths, exact
    except Exception:
        print("wa")
        return
    # exact p = points / 100000, 11 decimals, so Kontestis round(p * 100000) == round(points)
    print(f"custom:partial:{micro // 10**11}.{micro % 10**11:011d}")


if __name__ == "__main__":
    main()
