cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2020 · EasyIntervals

Meeting Friends

Autumn Tournament (2020)

Submission name: meeting.cpp

Problem summary

Two friends are available during inclusive minute intervals [l1, r1] and [l2, r2]. The second friend cannot talk in minute k because of a phone call. Find how many minutes they can talk.

Input

Five integers l1, r1, l2, r2, k.

Output

One integer: the number of available common minutes, or 0.

Constraints

1 ≤ l1, r1, l2, r2, k ≤ 50000; the endpoints describe availability intervals.

Worked example

Original statement, example 1.

Input

1 2 1 3 2

Output

1

Solution analysis

  1. The common interval begins at L = max(l1, l2) and ends at R = min(r1, r2). If L > R there is no shared minute.
  2. Otherwise the inclusive interval contains R − L + 1 minutes. Subtract one exactly when k belongs to that interval.
  3. For [1, 2] and [1, 3], the common minutes are 1 and 2. Removing minute 2 leaves one minute.

Why it works

A minute belongs to both intervals exactly when it lies between L and R. The formula counts precisely those minutes, and the subtraction removes precisely the only forbidden minute.

Complexity: O(1) time and O(1) extra space.

Watch out. Endpoints count as full minutes; do not subtract the phone minute when it lies outside the overlap.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    int l1,r1,l2,r2,k;
    cin>>l1>>r1>>l2>>r2>>k;
    int left=max(l1,l2);
    int right=min(r1,r2);
    int answer=max(0,right-left+1);
    // Only a phone call inside the common interval matters.
    if(left<=k&&k<=right){
        --answer;
    }
    cout<<answer<<'\n';
}

Source: Arena Olimpiici ↗