ExpertAlgorithms50 points

Bracket tags gone wrong

A forum in Warsaw lets users format posts with BBCode-like tags, for example [b]bold [i]and italic[/i][/b]. A moderation bot must reject posts whose tags are broken, and tell the author exactly where.

A tag token is [name] (opening) or [/name] (closing) where name is one or more lower-case letters. Everything else is plain text, including [B], [1], [] and [ b ]. Tag tokens are numbered 1, 2, 3 ... in order of appearance. The names br and hr are void tags: [br] needs no closing tag, and a closing [/br] is always an error. Every other tag must be closed in correct nesting order.

Task: line 1 is N; then N posts, one per line. Report the first problem for each post, numbering posts from 1:

  • Post i: OK when everything is balanced;
  • Post i: ERROR tag k: unexpected [/x] when the k-th tag token is a closing tag that does not match the innermost open tag (or nothing is open), where x is its name;
  • Post i: ERROR unclosed [x] when the post ends and tags are still open, where x is the innermost one.

Sample tests

Input

5
[b]bold [i]and italic[/i][/b]
[b]bold [i]crossed[/b][/i]
[b]never closed [i]x[/i]
nothing special [1] [B] []
[/b] starts with a closer

Expected output

Post 1: OK
Post 2: ERROR tag 3: unexpected [/b]
Post 3: ERROR unclosed [b]
Post 4: OK
Post 5: ERROR tag 1: unexpected [/b]

Input

2
line[br]break[hr]done
[u]under[br][/br][/u]

Expected output

Post 1: OK
Post 2: ERROR tag 3: unexpected [/br]

Your answer is also checked against 2 hidden tests.