problems / 270

Add Two Numbers Stored Backwards

easy linked-list math simulation 1000 ms · 256 MB

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.

Example 1

Input

3 3
2 1
3 2 0
1 4 3
2 3 1
3 5 0
1 4 2
2 6 3

Output

807

Example 2

Input

5 1
4 1
1 9 0
2 9 1
3 9 2
4 9 5
5 9 3
1 1 0

Output

100000

Hints · reveal one at a time if you're stuck

Hint 1

With up to 10^5 digits, the numbers don't fit in any built-in integer type, so you can't just convert each list to a number. Also, the records are not in list order: how can you get from a node to its next in O(1)?

Hint 2

Do column addition, the way you would on paper. The lists already give the ones digit first, which is the order column addition needs. Think about what happens when one list ends before the other, and when a carry is left after both have ended.

report an issue Prefer your own editor? sooks prep 270 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.