Problem solution · Turing

CCC 1996 P5 - Max Distance

CCC 1996 P5 - Max Distance: a Turing solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Direct simulation
Source
CCCSolutions
Length
54 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For CCC 1996 P5 - Max Distance, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 54 lines of Turing from the credited upstream file ccc96s5.t.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 1996 P5 - Max Distance · TuringTuring
Use this to learn the idea, then write your own version.
% CCC 1996% problem e Maximum Distance % calculate the max distance between two descending sequences% distance(xi,yj) = j-i if j>=i and yj >= xi (or 0 otherwise)% the distance between the sequences is the max distance for all i and j % file i/o used.% the first number is the number of sequence pairs.% each pair is preceeded by the size.  var infile : string := "max.in"var outfile : string := "max.out"var fi, fo : intvar n, d, j : intvar x, y : array 1 .. 1000 of intvar size : int open : fi, infile, getopen : fo, outfile, put get : fi, nfor k : 1 .. n     % get the sequences    get : fi, size    for i : 1 .. size        get : fi, x (i)    end for    for i : 1 .. size        get : fi, y (i)    end for     % for each number in x, work backward thru y to find the last position of    % y(j) >= x(i). If j > i and j-i > previous max, save it in max (d)    d := 0    for i : 1 .. size        j := size        loop            exit when j <= i or y (j) >= x (i)            j := j - 1        end loop        if j > i and j - i > d then            d := j - i        end if    end for    put : fo, "The maximum distance is ", d    put : fo, ""end forclose : ficlose : fo  

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗