/* SWERC'97 - Instant Complexity */
/*  11/7/97 - Matthias Ruhl      */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

int *runtime()
{
  int *p,*q;
  int i,v;
  char s[10];
  
  p = (int *) calloc(11,sizeof(int));
  while(1)
    {
      scanf(" %s",s);
      switch(s[0])
	{
	case 'E': /* END */
	  return p;
	case 'O': /* OP */
	  scanf("%d",&v);
	  p[0] += v;
	  break;
	case 'L': /* LOOP */
	  /* LOOP statement */
	  scanf(" %s",s);
	  q = runtime();
	  if(s[0] == 'n')
	    for(i=10;i>0;i--) p[i] += q[i-1];
	  else
	    {
	      v = atoi(s);
	      for(i=0;i<11;i++) p[i] += v*q[i];
	    }
	  free(q);
	  break;
	default:
	  printf("ERROR"); exit(0);
	}
    }
}

void output(int *p)
{
  int i,pr=0;

  printf("Runtime = ");
  for(i=10;i>=0;i--)
    if(p[i])
      {
	if(pr) printf("+");
	if(i == 0) printf("%d",p[i]);
	else
	  {
	    if(p[i] != 1) printf("%d*",p[i]);
	    printf("n");
	    if(i > 1) printf("^%d",i);
	  }
	pr = 1;
      }
  if(!pr) printf("0");
  printf("\n\n");
  free(p);
}

int main()
{
  int i,k;
  char s[10];

  scanf("%d",&k);
  for(i=0;i<k;i++)
    {
      printf("Program #%d\n",i+1);
      scanf("%s",s);
      assert(strcmp(s,"BEGIN") == 0);
      output(runtime());
    }

  return 0;
}
