HIMYMCV - Editorial

PROBLEM LINK:

How I met your Mother

Author: Halry Bhalodia
Tester: Rishabh Rathi

DIFFICULTY:

CAKEWALK

PREREQUISITES:

Simple Geometry

PROBLEM:

Ted’s house was present at x=x_1, Robin’s house was at x=x_2 and Barney’s house was at x=x_3 (All houses are present on X-axis). Barney has arranged lasers around his house in a circle of a certain radius R, i.e. from x=x_3, there are lasers at a distance ≤ R on both sides so that he can save his best bro from being committed in a relationship.

Find out how much distance will Ted walk without struggling in the laser.

EXPLANATION:

Total distance between Ted and Robin’s house = |x_1-x_2|

Following are the cases:

  1. If circle is covering none of Ted’s and Robin’s house → ans is total distance
  2. If Robin and Ted live in same house → ans is 0
  3. If radius of circle is 0 → ans is total distance
  4. If the circle is between Ted’s and Robin’s house but does not cover them → then ans is [total distance – (2*R)]
  5. If circle is between Ted’s and Robin’s house and completely cover them → then ans is 0
  6. If circle covers left house → then ans is [total distance – (x_3 + R - min(x_1, x_2))]
  7. If circle covers right house → then ans is [total distance – (max(x_1,x_2) – (x_3-R))]

SOLUTIONS:

Setter's Solution - Python
t = int(input())

for i in range(t):
	x1, x2, x3, r = list(map(int,input().split()))

	l = x3-r
	h = x3+r

	a, b = min(x1, x2), max(x1, x2)
	tot = b - a

	if h<a or l>b:
		ans = tot
	elif tot == 0:
		ans = 0
	elif r == 0:
		ans = tot
	elif l>=a and h<=b:
		ans = tot-(2*r)
	elif l<=a and h<=b:
		ans = tot-(h-a)
	elif l>=a and b<=h:
		ans = tot-(b-l)
	else:
		ans = 0

	print(ans)
Tester's Solution - Cpp
#include <bits/stdc++.h>  
using namespace std;

typedef long long ll;

int main() {
	ios_base::sync_with_stdio(0);  cin.tie(0);
	ll t, x1, x2, x3, r, left, right, a, b, total, ans;

	cin>>t;

	while(t--) {
		cin>>x1>>x2>>x3>>r;

		left = x3-r;
		right = x3+r;

		a = min(x1, x2);
		b = max(x1, x2);

		total = b - a;

		if (right<a || left>b)
			ans = total;
		else if (total == 0)
			ans = 0;
		else if (r == 0)
			ans = total;
		else if (left>=a && right<=b)
			ans = total-(2*r);
		else if (left<=a && right<=b)
			ans = total-(right-a);
		else if (left>=a && b<=right)
			ans = total-(b-left);
		else
			ans = 0;

		cout<<ans<<endl;
	}
	return 0;
}

Feel free to share your approach. In case of any doubt or anything is unclear please ask it in the comment section. Any suggestions are welcomed. :smile: