Official

D - Intersection of Cuboids Editorial by en_translator


Let \([x,y]\) denote the segment formed by all real numbers between \(x\) and \(y\), inclusive.

First, let us consider a one-dimensional problem.

one-dimensional problem

Problem: determine if two segments \([a,b]\) and \([c,d]\) has an intersection of a positive length.

There are various ways to determine it. One ways is to check if the intersection has a length of \(0\), and take its negation. The length of intersection is \(0\) for one of the following cases:

  • \([a,b]\) is to the left of \([c,d]\).
  • \([a,b]\) is to the right of \([c,d]\).

In Pythonic pseudocode, it can be written as follows:

if b <= c  or  d <= a:
  print("0 intersection")
else:
  print("positive intersection")

three-dimensional problem

Solve the one-dimensional problem for the three coordinates \(x\), \(y\), and \(z\); if the length of the intersection is all positive, then the intersection of the cuboids has a positive volume; otherwise, it is \(0\).

Why? If the length of the intersection of the segments for the $x$ coordinate is $0$, then (just as the one-dimensional problem) one cuboid is "to the left" of the other, so the intersection has a volume of $0$. Same applies to $y$ and $z$ coordinates.
Conversely, if the length of the intersection for $x$, $y$, and $z$ coordinates are all possible, then any point whose coordinates are in the ranges is contained in the intersection of the cuboids, so the volume is positive.

As we are solving one-dimensional problem three times, it is good idea to extract that part into a function in order to simplify the implementation.

Sample code (Python)

x1,y1,z1,x2,y2,z2 = map(int,input().split())
x3,y3,z3,x4,y4,z4 = map(int,input().split())

def f(l1,r1,l2,r2):
  # returns True if the intersection of [l1,r1] and [l2,r2] has a positive length
  return not (r1<=l2 or r2<=l1)

if f(x1,x2,x3,x4) and f(y1,y2,y3,y4) and f(z1,z2,z3,z4):
  print("Yes")
else:
  print("No")

posted:
last update: