import sys
from pathlib import Path


def fail(msg: str) -> None:
    """Fail WA with given message"""
    with open(sys.argv[3] / Path("judgemessage.txt"), "a", encoding="utf-8") as jfile:
        jfile.write(f"WA: {msg}\n")
    sys.exit(43)


def accept() -> None:
    sys.exit(42)


def get_team_answer() -> list[str]:
    team_bytes = sys.stdin.buffer.read()
    try:
        team_lines = team_bytes.decode("utf-8").splitlines()
    except UnicodeDecodeError:
        fail("Team answer contains unexpected characters")
    if not team_lines:
        fail("Submission produces empty output")
    return team_lines


def token_to_id(t: str) -> int:
    try:
        token_id = int(t)
    except ValueError:
        fail(f"Unable to parse {t} as integer")
    return token_id


with open(sys.argv[1]) as in_file, open(sys.argv[2]) as ans_file:
    N, H, W = map(int, in_file.readline().split())
    books = [tuple(map(int, in_file.readline().split())) for _ in range(N)]

    team = " ".join(get_team_answer())
    impossible_instance = "impossible" in ans_file.readline()

    if team.strip().lower() == "impossible":
        if not impossible_instance:
            fail("Submission falsely rejects possible instance")
        else:
            accept()


    tokens = team.split()
    if len(team) == 0:
        fail("Submission produces no tokens")

    orientation = None
    for token in tokens:
        if orientation is None:
            if token.lower() != "upright":
                fail(f"Expected the word 'upright', got {token}")
            orientation = "upright"
            upright: list[int] = []
        elif orientation == "upright":
            if token.lower() == "stacked":
                orientation = "stacked"
                stacked: list[int] = []
            else:
                upright.append(token_to_id(token))
        else:
            assert orientation == "stacked"
            stacked.append(token_to_id(token))

    if len(upright) == 0:
        fail("No upright books")
    if len(stacked) == 0:
        fail("No stacked books")

    allbooks = upright + stacked
    if list(sorted(allbooks)) != list(range(1, N + 1)):
        fail("Book indices differ from 1..N")

    is_ordered = all(
        books[i - 1][0] >= books[j - 1][0] for i, j in zip(stacked, stacked[1:])
    )
    if not is_ordered:
        fail("Stacked books out of order")

    stack_width = books[stacked[0] - 1][0]
    stack_height = sum(books[i - 1][1] for i in stacked)
    upright_width = sum(books[i - 1][1] for i in upright)
    if stack_width + upright_width > W:
        fail(f"Total width exceeded: {stack_width + upright_width} > {W}")
    if stack_height > H:
        fail(f"Stack too tall: {stack_height} > {H}")
    for i in upright:
        if books[i - 1][0] > H:
            fail(f"Book {i} does not fit upright: {books[i-1][0]} > {H}")

    if impossible_instance:
        assert False, "JE: Judge answer rejects instance, but valid solution exists"

    accept()
