Largest Honest Subtree
The Guild of Lanterns keeps its lineage in one long line of text. Every member has a rank, a signed integer, and has trained at most two apprentices: a left apprentice and a right apprentice. A member together with all their apprentices, the apprentices' apprentices and so on is called that member's branch.
A branch is honest if, for every member m in it, every rank in the branch of m's left apprentice is strictly smaller than m's rank, and every rank in the branch of m's right apprentice is strictly larger than m's rank. Every rank in a sub-branch counts, not just the apprentice's own: a member deep down on the right side of m with a rank smaller than m's makes the branch of m dishonest. Two members with equal rank can never both be in an honest branch where one is below the other.
Find the honest branch with the most members. If several honest branches have the same size, pick the one whose ranks have the largest total. Print its size and the total of its ranks.
The lineage is written with this grammar:
tree := key
| key "(" child "," child ")"
child := tree
| (empty)
keyis a rank written in decimal: an optional-followed by digits, without leading zeros (0is written as0, never-0or00). Every rank satisfies-2^31 ≤ key ≤ 2^31 - 1.- In
key(A,B),Ais the left apprentice's branch andBis the right one's. Either may be empty:5(,7)has only a right apprentice,5(3,)only a left one, and5(,)none at all, which means the same as a bare5. The comma is always present. - Any number of spaces may appear before or after any key, parenthesis or comma, but never inside a key (between the
-and the digits, or between digits).
Input
A single line of at most 10^6 characters containing one tree (so there is at least one member), followed by a newline. The line contains only digits, -, (, ), , and spaces, and always follows the grammar above.
The depth of the tree, the number of members on the longest path going from the root down through apprentices, is at most 10^5.
Output
Print two integers separated by a space: the number of members in the chosen honest branch, and the sum of their ranks.
Notes
A single member with no apprentices is always an honest branch, so an answer always exists.
In the first example the whole tree is not honest: 45 is in the right branch of 50 but is smaller than 50. Both 30(20,40) and 70(45,80) are honest branches with 3 members; their totals are 90 and 195, so the answer is 3 195.
In the second example -5(,-3) is honest with 2 members and total -8. The branch 7( 7, ) is not honest because of the repeated rank, and so the whole tree isn't either.
The deepest trees do not fit in a default-sized call stack in some languages; parse iteratively or make sure your recursion has enough stack.