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
- The common interval begins at L = max(l1, l2) and ends at R = min(r1, r2). If L > R there is no shared minute.
- Otherwise the inclusive interval contains R − L + 1 minutes. Subtract one exactly when k belongs to that interval.
- 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.
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';
}