A pair of acoustic engineers each recorded a resonance spectrum from the same instrument on different days. Each spectrum is written as a sequence of terms, where every term has an integer amplitude and a distinct non-negative integer frequency index, and the terms in each spectrum are listed in strictly decreasing order of frequency (no two terms in the same spectrum share a frequency).
The engineers want to fuse their two spectra into one combined reading: for every frequency that appears in either spectrum, the fused amplitude at that frequency is the sum of the amplitudes contributed by each original spectrum (treating a frequency missing from a spectrum as contributing amplitude 0). If a fused amplitude comes out to exactly 0, that frequency is omitted entirely from the fused spectrum — it did not survive the fusion.
Given both spectra, output the fused spectrum, listing its terms in strictly decreasing order of frequency.
Line 1: an integer n1, the number of terms in the first spectrum.
Each of the next n1 lines: two integers amp freq — a term of the first spectrum. Frequencies strictly decrease from one line to the next.
Next line: an integer n2, the number of terms in the second spectrum.
Each of the next n2 lines: two integers amp freq — a term of the second spectrum, frequencies strictly decreasing.
Line 1: an integer k, the number of terms in the fused spectrum.
Each of the next k lines: two integers amp freq, the fused spectrum's terms in strictly decreasing order of frequency. If k = 0, print only the line containing 0.
Example 1
Input
3 5 4 2 2 9 0 3 3 4 -2 2 -9 0
Expected
1 8 4
Explanation
Spectrum 1 has terms (5,4),(2,2),(9,0); spectrum 2 has (3,4),(-2,2),(-9,0). At frequency 4: 5+3=8. At frequency 2: 2+(-2)=0, so it is dropped. At frequency 0: 9+(-9)=0, so it is dropped too. The fused spectrum has one term, (8,4), so the output is `1` followed by `8 4`.
Example 2
Input
2 1 5 2 1 2 4 3 1 0
Expected
4 1 5 4 3 2 1 1 0
Explanation
The frequencies present are 5, 3, 1, 0 — all distinct between the two spectra, so no amplitude combines with another. Merging by strictly decreasing frequency gives (1,5), (4,3), (2,1), (1,0), so the output is `4` followed by those four lines in that order.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →