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 C2011 · MediumIntervals

Intersection of Two Segments

National Olympiad — Municipal round

Submission name: segments.cpp

Problem summary

Two closed segments on the number line have integer endpoints a,b and c,d, which may be given in either order. Find the length of their intersection, or report no intersection.

Input

Four integers a b c d.

Output

Intersection length, or −1 if the segments have no common point.

Constraints

−100≤a,b,c,d≤100.

Worked example

An independently prepared example for this explanation.

Input

7 2 4 9

Output

3

Solution analysis

  1. Normalize each endpoint pair.
  2. The intersection starts at the larger left endpoint and ends at the smaller right endpoint.
  3. A reversed intersection is empty; equal endpoints mean length zero.

Why it works

A point is in both closed segments precisely when it is at least both left endpoints and at most both right endpoints.

Complexity: O(1) time and space.

Watch out. A single shared endpoint gives 0, not −1.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: A point is in both closed segments precisely when it is at least both left endpoints and
// at most both right endpoints.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    if(a>b){
        swap(a,b);
    }
    if(c>d){
        swap(c,d);
    }
    int l=max(a,c),r=min(b,d);
    cout<<(l>r?-1:r-l)<<'\n';
}

Source: Arena Olimpiici ↗