cppAcademy
FROM LEARNING TO COMPETING

Real problems.
Your next challenge.

Explore the Group C Olympiad archive.
Choose a topic. Find a challenge. Build your solution.

213 tasks across the Municipal, Regional, and National rounds (2009–2026), plus 4 previously featured problems. 146 tasks have independently written English summaries, analyses, and C++17 solutions; the remaining entries link to Arena. Topic tags are from Arena or our reviewed explanations. Difficulty labels are learning estimates, not official ratings.
GROUP C2017 · MediumInterval Merging

Union of Integer Sets

National Olympiad — Municipal round

Submission name: set.cpp

Problem summary

Each of N sets contains every integer from Ai through Bi. Express their union as the minimum number of integer intervals, listed in increasing order.

Input

N, then N pairs Ai Bi.

Output

Number M of resulting intervals, then their M endpoint pairs in increasing order of left endpoint.

Constraints

1≤N≤10000; 1≤Ai<Bi≤10^9.

Worked example

An independently prepared example for this explanation.

Input

3
2 4
5 7
10 11

Output

2
2 7
10 11

Solution analysis

  1. Sort intervals by their left endpoint.
  2. Merge an interval whenever its start is at most the current end plus one; integer adjacency leaves no missing integer.
  3. Otherwise finish the current interval and begin a new one.

Why it works

After sorting, every next interval either extends the current consecutive block or starts beyond a missing integer. In the latter case no later interval can fill the gap, so a separate block is necessary.

Complexity: O(N log N) time and O(N) space.

Watch out. Merge adjacent integer intervals as well as overlapping ones.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: After sorting, every next interval either extends the current consecutive block or starts
// beyond a missing integer. In the latter case no later interval can fill the gap, so a separate block
// is necessary.
#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<iterator>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<pair<long long,long long>>a(n),b;
    for(auto&[l,r]:a){
        cin>>l>>r;
    }
    sort(a.begin(),a.end());
    for(auto[l,r]:a){
        if(b.empty()||l>b.back().second+1){
            b.push_back({l,r});
        }
        else{
            b.back().second=max(b.back().second,r);
        }
    }
    cout<<b.size()<<'\n';
    for(auto[l,r]:b){
        cout<<l<<' '<<r<<'\n';
    }
}

Source: Arena Olimpiici ↗