Add Two Numbers Stored Backwards
Two non-negative integers A and B are each stored as a singly linked list of decimal digits,
ones digit first: the head node holds the last digit of the number, the node after it holds the
tens digit, and so on, and the tail node holds the most significant digit.
The nodes of the first list are numbered 1 to n and the nodes of the second list are numbered 1
to m (the two numberings are independent). Each node is given as a record id d next: its id, its
digit d, and the id of the following node in the same list, or 0 if this node is the tail. The
records are listed in arbitrary order, not in list order, so you have to follow the next
pointers from the heads.
Print A + B.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5), the number of nodes in the
first and second list.
The second line contains two integers a and b (1 ≤ a ≤ n, 1 ≤ b ≤ m), the ids of the
head nodes of the first and second list.
Each of the next n lines contains three integers id d next (1 ≤ id ≤ n, 0 ≤ d ≤ 9,
0 ≤ next ≤ n) describing a node of the first list. Each of the following m lines describes a
node of the second list in the same way, with 1 ≤ id ≤ m and 0 ≤ next ≤ m.
Every id appears in exactly one record of its list, and starting at the head and following next
visits every node of that list exactly once and ends at 0. Numbers have no leading zeros: the tail
digit of a list is non-zero unless that list is the single digit 0.
Output
Print the decimal digits of A + B on one line, most significant digit first, without leading zeros
and without spaces.
Notes
In the first example the first list read from its head 2 is 3, 4, 2, so A = 243; the second
list read from its head 1 is 4, 6, 5, so B = 564. The sum is 807.
In the second example A = 99999 and B = 1. The carry runs through every digit and creates a new
most significant digit, giving 100000.
The numbers can have up to 10^5 digits, far beyond any built-in integer type, so add them digit by digit.