{$R+,S+}

uses
  testlib, sysutils;

function format (str: string; pos: integer): string;
var bg, en: integer;
begin
  if length (str) < pos - 1 then quit (_fail, 'Position is not in str');
  if pos > 30 then bg := pos - 30 else bg := 1;
  if length (str) - pos > 30 then en := pos + 30 else en := length (str);
  format := copy (str, bg, pos-bg) + '[' + copy (str, pos, 1) + ']' + 
            copy (str, pos+1, en-(pos+1))
end;

procedure check_expr (str: string);
var
  opened: integer;  
  term_begin: boolean;
  term_end: boolean;
  i: integer;

  procedure wa (msg: string);
  begin Quit (_wa, msg + ': ' + format (str, i)); end;

  procedure pe (msg: string);
  begin Quit (_pe, msg + ': ' + format (str, i)); end;

  procedure assert_begin;
  begin
    if not term_begin then wa ('Unexpected symbol - term cannot begin here');
  end;

  procedure assert_end;
  begin
    if not term_end then wa ('Unexpected symbol - term cannot end here');
  end;

begin
  term_begin := true;
  term_end := false;
  opened := 0;

  for i := 1 to length (str) do begin
    case str [i] of
      '0'..'9': begin assert_begin; term_end := true; end;
      '(': begin assert_begin; inc (opened); term_end := false; end;
      ')': begin assert_end; dec (opened); if opened < 0 then wa ('Unmatched )'); end;
      '+': begin assert_end; term_end := false; term_begin := true; end;
      else begin pe ('Unexpected symbol'); end;
    end
  end;

  i := length (str) + 1;
  if not term_end then wa ('Unexpected end of string');
  if opened > 0 then wa ('Unmatched ('); 
  if opened < 0 then Quit (_fail, 'Unmatched ) - ???');
end;

function trace (source, target: string): integer;
var i: integer;
  p: integer;
begin
  p := 1;
  for i := 1 to length (source) do begin
    if length (target) < p then begin
      trace := i;
      exit
    end;
    while (source [i] <> target [p]) do begin
      inc (p);
      if length (target) < p then begin
        trace := i;
        exit
      end;
    end;
    inc (p);
  end;
  trace := 0
end;

var
  corrupted, answer: string;
  pos: integer;

begin
  corrupted := inf.readstring;
  answer := ouf.readstring;

  check_expr(answer);
    
  pos := trace(corrupted, answer);
  if pos <> 0 then begin
    quit(_WA, 'Cannot find trace of symbol ' + format(corrupted, pos));
  end;

  if length(answer) >= 5000 then begin
    quit(_WA, 'answer is too long: ' + intToStr(length(answer)));
  end;

  quit(_OK, '');
end.
