
ZOJ Problem Set  1401
David Hilbert proved the existence of a very counterintuitive curve that fills space. The construction of the Hilbert curve is based on a sequence of curves, H1, H2, H3, H4, ... composed of horizontal and vertical segments. Each curve lies in the unit square [0, 1] �� [0, 1]. H1 contains just three segments, connecting the points (1/4, 3/4) to (1/4, 1/4) to (3/4, 1/4) to (3/4, 3/4). Hn is defined recursively in terms of Hn1, for n = 2, 3, ... by four transformations: Halve all coordinates in Hn1. Figure 1 Figure 2 The coordinates of vertices of Hn are odd multiples of ?n+1. The coordinates of horizontal segment endpoints will always be multiples of ?n. Hence the specified horizontal segment can only cross vertical segments in Hn. Input consists of one to 100 data sets, one per line, followed by a final line containing only 0. Each data set consists of four integers separated by blanks in the form n x1 x2 y The output is one integer per line for each data set: the number of intersections of Hn with the segment. Caution: A brute force solution that computes each intersection individually will not finish within the one minute time limit. As you can see below, there may be more than one billion intersections for any data set.
3 2 7 7
3 Source: MidCentral USA 2002 