#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#define LIBMAXLEN 1000
#define LIBMAXDWARFES 1000

char LIBinitialized = 0;

struct LIBlist {
  struct LIBlist *next;
  int i;
}*LIBp;

struct LIBdwarfes {
  int c;
  struct LIBlist *p[2];
}LIBd[LIBMAXDWARFES];

int LIBtype[LIBMAXLEN],LIBf,LIBl,LIBn,LIBact;

FILE *LIBout;

void LIBreport(int EXIT, char *fmt, ...) {
  va_list ap;
  va_start( ap, fmt );

  vfprintf( LIBout, fmt, ap );
  if ( fmt[ strlen(fmt)-1 ] != '\n' ) fprintf(LIBout,"\n");
  if (EXIT){
    exit (0);
  }
}

void init() {
  int n,l,i,j,p;
  FILE *in = fopen("pearls.in","r");
  LIBout = stdout;

  if (!in) LIBreport(1, "cannot open pearls.in");
  if (fscanf(in,"%d %d %d",&l,&n,&LIBf)!=3) LIBreport(1, "error in pearls.in");

  LIBinitialized = 1;
  LIBact = 0;
  LIBn = n;
  LIBl = l;
  LIBf--;

  LIBreport(0, "init()");
  for (i=0; i<l; i++){
    char c;
    if (fscanf(in," %c",&c)!=1 || c!='B' && c!='W' && (i<l-1 || c!='D'))
      LIBreport(1,"Error in pearls.in");
    LIBtype[i] = (c == 'W');
  }

  for (i=0; i<n; i++) {
    if (fscanf(in,"%d",&LIBd[i].c)!=1) LIBreport(1,"Error in pearls.in");
    for (j=0; j<2; j++) {
      int len;
      LIBd[i].p[j] = NULL;
      if (fscanf(in,"%d",&len)!=1) LIBreport(1,"Error in pearls.in");
      while(len--) {
	int temp;
	if (fscanf(in,"%d",&temp)!=1) LIBreport(1,"Error in pearls.in");
	LIBp = (struct LIBlist *)malloc(sizeof(struct LIBlist));
	LIBp->i = temp-1;
	LIBp->next = LIBd[i].p[j];
	LIBd[i].p[j] = LIBp;
      }
    }
  }
  fclose(in);

}

void finish() {
  if (!LIBinitialized) init();
  LIBreport(0, "finish()");
  int i;
  if (LIBact!=LIBl-1) LIBreport(1,"called finish() but end of game is not reached");
  if (LIBd[LIBf].c==1)
    LIBreport(1,"red dwarfs have won");
  LIBreport(1, "green dwarfs have won");
}

int getNext() {
  if (!LIBinitialized) init();
  if (LIBact>=LIBl-1) LIBreport(1,"too many calls to getNext()/setNext()");
  if (LIBd[LIBf].c==0)LIBreport(1,"called getNext() but %d is a green dwarf", LIBf+1);
  LIBf = LIBd[LIBf].p[LIBtype [LIBact]]->i;
  LIBreport(0, "getNext() -> %d", LIBf+1);
  LIBact++;
  return LIBf+1;
}

void setNext(int dwarfes) {
  if (!LIBinitialized) init();
  if (LIBact>=LIBl-1) LIBreport(1,"too many calls to getNext()/setNext()");
  if (LIBd[LIBf].c==1)LIBreport(1,"called setNext() but %d is a red dwarf", LIBf+1);
  LIBp = LIBd[LIBf].p[LIBtype[LIBact]];
  while(LIBp!=NULL) {
    if (LIBp->i == dwarfes-1) {
      LIBf = LIBp->i;
      break;
    }
    LIBp = LIBp->next;
  }
  if (LIBp == NULL) {
    LIBreport(1, "no dwarf with number %d in list of dwarf %d", dwarfes, LIBf+1);
  }
  LIBreport(0, "setNext(%d)", dwarfes);
  LIBact++;
}
