RL :=
proc(n, k)
    option remember;
    local ind, d, pos, cur, run, runs, res;

    res := 0;

    for ind from 3^n to 2*3^n-1 do
        d := convert(ind, base, 3);

        cur := -1; pos := 1;
        run := []; runs := [];


        while pos <= n do
            if d[pos] <> cur then
                if nops(run) > 0 then
                    runs := [op(runs), run];
                fi;

                cur := d[pos];
                run := [cur];
            else
                run := [op(run), cur];
            fi;

            pos := pos + 1;
        od;

        runs := [op(runs), run];

        if max(map(r->nops(r), runs)) <= k then
            for pos to nops(runs) -1 do
                run := runs[pos];

                if run[1] = 1 and nops(run) = k
                and runs[pos+1][1] = 2 then
                    break;
                fi;
            od;

            if pos < nops(runs) then
                res := res + 1;
            fi;
        fi;
    od;

    res;
end;

RNG := (minv, maxv) -> add(z^q, q=minv..maxv);

H :=
proc(k)
    RNG(1,k)*
    sum((RNG(1,k)*RNG(1,k))^q, q=0..infinity)
    *RNG(0,k)
end;


H2 := 
proc(k) 
    z*(1-z^k-z^(k+1)+z^(2*k+1))
    /(1-2*z+2*z^(k+2)-z^(2*k+2));
end;

G := 
proc(k)
    (1+2*H(k))
    *sum((RNG(1,k-1)*2*H(k)
          + z^k*(1+v)*H(k))^q,
         q=0..infinity)
    *RNG(0, k);
end;

G2 := 
proc(k)
    (1+2*H2(k))*(1-z^(k+1))
    /(1-z-H2(k)*(2*z-2*z^k+z^k*(1+v)*(1-z)));
end;

Q :=
proc(k)
    subs(v=1, G(k)-subs(v=0, G(k)));
end;

Q2 :=
proc(k)
    (1+2*H2(k))*(1-z^(k+1))
    /(1-z-H2(k)*(2*z-2*z^(k+1)))
    - (1+2*H2(k))*(1-z^(k+1))
    /(1-z-H2(k)*(2*z-z^k-z^(k+1)));
end;

V :=
proc(n, k)
    option remember;

    coeftayl(Q2(k), z=0, n);
end;