{$Q+,r+}
const
    max_n = 2000;
var
    i, j, k, n: longint;
    a: array [1..2 * max_n, 1..max_n] of longint;
    c: array [1..2 * max_n] of longint;
    u: array [0..2 * max_n] of longint;
    s: array [1..4 * max_n] of longint;
    q: array [1..max_n, 1..max_n] of boolean;
    m: longint;

procedure dfs(i, k: longint);
var
    j: longint;
begin
    u[i] := k;
    for j := 1 to c[i] do begin
        if (u[a[i][j]] = 0) then begin
            dfs(a[i][j], k);
        end;
    end;
    inc(m);
    s[m] := i;
end;

var
    b: longint;
begin
    while not seekeof do begin
        fillchar(a, sizeof(a), 0);
        fillchar(c, sizeof(c), 0);
        fillchar(u, sizeof(u), 0);
        fillchar(s, sizeof(s), 0);
        fillchar(q, sizeof(q), 0);

        read(n);
        for i := 1 to n do begin
            read(c[i]);
            for j := 1 to c[i] do begin
                read(a[i][j]);
                q[i][a[i][j]] := true;
            end;
        end;

        for i := 1 to n do begin
            c[i + n] := 1;
            read(b);
            a[i + n][1] := b;
            for j := 1 to c[i] do begin
                if a[i][j] = b then begin
                    a[i][j] := 0;
                end;
            end;
        end;

        fillchar(u, sizeof(u), 0);
        u[0] := n + 1;
        m := 0;
        for i := 1 to n * 2 do begin
            if (u[i] = 0)then begin
                dfs(i, 1);
            end;
        end;

        k := 0;
        fillchar(u, sizeof(u), 0);
        u[0] := n + 1;
        for i := 1 to n do begin
            if (u[s[i]] = 0)then begin
                inc(k);
                dfs(s[i], k);
            end;
        end;

        for i := 1 to n do begin
            k := 0;
            for j := 1 to n do begin
                if ((u[i] = u[j]) or (i = a[j + n][1])) and q[i][j] then begin
                    inc(k);
                end;
            end;
            write(k);
            for j := 1 to n do begin
                if ((u[i] = u[j]) or (i = a[j + n][1])) and q[i][j] then begin
                    write(' ', j);
                end;
            end;
            writeln;
        end;
        writeln;
    end;

    close(input);
    close(output);
end.