Distance to Interval
Programming Basics · C++
TASK
Problem
In “Distance to Interval”, solve the stated coordinate or interval relation using integer comparisons.
EXAMPLE
Example
3 0 10
0
LIMITS
Constraints
Coordinate magnitudes are at most 10^9; interval endpoints are given in nondecreasing order.
LEARN
Theory for this problem
+
Coordinate tasks often reduce to comparisons, absolute differences, `min`, and `max`.
Connection to “Distance to Interval”: here, intermediate values are best kept in named variables so the formula stays readable and data types remain clear.
NEED HELP?
Hints
+
['Translate the geometry into inequalities before coding.', 'After solving “Distance to Interval”, verify the algorithm on your own small example and on an allowed boundary case. Print only the required result with no extra text.']
ANSWER
Solution
+
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
long long x,l,r;
cin >> x >> l >> r;
long long ans=(l<=x&&x<=r)?0:min(llabs(x-l),llabs(x-r));
cout << ans << '\n';
return 0;
}