ProbD := proc(infile, outfile)
  local infd, outfd, m, pre, post, pre_cmp, post_cmp, len, i, j, descendants, 
        children, calc_children, ans;

  calc_children := proc(start, len)
    local root, i, subtree_len;

    root := pre[start];
    i := 1;
    while i < len do
      children[root] := children[root] + 1;
      subtree_len := 1 + descendants[pre[start+i]];
      calc_children(start+i, subtree_len);
      i := i + subtree_len;
    od;
  end;

  infd := fopen(infile, READ);
  outfd := fopen(outfile, WRITE);

  m := op(fscanf(infd, "%d"));
  while m > 0 do
    pre, post := op(fscanf(infd, "%s %s"));
    pre_cmp := array(0..25,0..25,[[false$26]$26]);
    post_cmp := array(0..25,0..25,[[false$26]$26]);

    pre := map(x->StringTools[Ord](x) - StringTools[Ord]("a"),
               convert(pre, list));
    post := map(x->StringTools[Ord](x) - StringTools[Ord]("a"),
                convert(post, list));
    len := nops(pre);

    for i from 1 to len do
      for j from i+1 to len do
        pre_cmp[pre[i],pre[j]] := true;
        post_cmp[post[i],post[j]] := true;
      od;
    od;

    descendants := array(0..25, [0$26]);
    for i from 0 to len-1 do
      for j from 0 to len-1 do
	if pre_cmp[i,j] and post_cmp[j,i] then
          descendants[i] := descendants[i] + 1;
        fi;
      od;
    od;

    children := array(0..25, [0$26]);
    calc_children(1, len);
    
    ans := mul(binomial(m, children[i]), i=0..25);
    if ans > 2^31-1 then
      fprintf(outfd, "**BAD** ");
    fi;
    fprintf(outfd, "%d\n", ans);
    m := op(fscanf(infd, "%d"));
  od;

  fclose(infd);
  fclose(outfd);
end:
