#C7902. Non-Overlapping Interval Insertion

    ID: 51825 Type: Default 1000ms 256MiB

Non-Overlapping Interval Insertion

Non-Overlapping Interval Insertion

You are given a set of current intervals and a set of new intervals. Your task is to insert each new interval into the current intervals only if it does not overlap with any of the current intervals.

An interval is defined as a pair of integers \( (start, end) \) with \( start < end \). Two intervals \( (a, b) \) and \( (c, d) \) are considered overlapping if they satisfy the condition:

[ \neg(b \leq c \quad \text{or} \quad d \leq a) ]

After processing, the resulting list of intervals should include all of the original intervals along with any new intervals that did not overlap with them. The intervals in the final result must be output in increasing order by their starting value.

Note: Process multiple test cases from the input.

inputFormat

The input is provided via standard input. It consists of multiple test cases. Each test case is structured as follows:

  • The first line contains an integer \(N\) indicating the number of current intervals.
  • The next \(N\) lines each contain two integers separated by a space representing an interval (start and end).
  • The following line contains an integer \(M\) indicating the number of new intervals.
  • The next \(M\) lines each contain two integers separated by a space representing a new interval.

There is no separate number specifying the total number of test cases; the input ends when all test cases have been provided.

outputFormat

For each test case, output the resulting intervals in a single line using standard output. The intervals should be printed in sorted order (by their start value) and formatted as follows: each interval is printed as two integers separated by a space, and intervals are separated by a comma and a space. For example, if the resulting intervals are \((1, 3)\), \((6, 9)\) and \((10, 20)\), the output should be:

1 3, 6 9, 10 20
## sample
2
1 3
6 9
3
2 5
8 10
10 20
1 3, 6 9, 10 20