import java.io.*; import java.util.*; import java.awt.*; import java.text.*; import java.math.*; /** * Solution for The Ninja Way * * This program will use a Greedy algorithm. First, it'll assume that the trees are * laid out right next to each other, as tightly as possible. Then, it'll find the * positions of the smallest and largest trees - let's say s and t - and then try to * stretch the gap between s and s+1 as far as possible, then the gap between s+1 and s+2, * then s+2 and s+3, all the way up to t-1 and t. It will look at all pairs of trees that * are adjacent height-wise (that the Ninjas would jump between) that span each of those gaps, * to see how far the gaps can be stretched. * * The only way the Greedy algorithm can fail is if stretching an early gap limits your * options of stretching a later gap. I'm not going to go through a convoluted argument, * but it's true. It's left as an exercise to the reader to confirm! */ class ninjaway { public Scanner sc; public PrintStream ps; public String toString() { return "ninjaway"; } /** * The main method */ public void doit() throws Exception { sc = new Scanner( System.in ); // new Scanner( new File( "ninjaway.judge" ) ); ps = System.out; // new PrintStream( new FileOutputStream( "ninjaway.solution" ) ); for(;;) { // Read in n & d, exit if at end int n = sc.nextInt(); int d = sc.nextInt(); if( n==0 ) break; // The trees, in order of input int trees[] = new int[n]; // An array to sort the trees by height int sorted[] = new int[n]; // Read in the trees for( int i=0; id ) failed=true; } // This'll be our answer int total; // if we failed, then the answer is -1 if( failed ) { total = -1; } else { // OK, it gets a little confusing here. We're going to have two indexing schemes. // i is going to represent height order (i==0 is the smallest tree), and // j is going to represent order on the ground (j==0 is the first tree in the input) // This will hold true throughout the rest of the code. // // spans[i][j] is true if the space between trees i and i+1 spans gap j. // That is, if the space between trees i and i+1 (in height order) crosses // the gap between trees j and j+1 (on the ground), then span[i][j] is true. boolean spans[][] = new boolean[n][n]; for( int i=0; iD. int maxdist = 0; for( int i=0; imaxdist ) { maxdist=dist[i]; } } // The best we can do is to stretch that biggest // gap to be D. int stretch = d-maxdist; // Add in the amount of this stretch total += stretch; // OK, stretch that gap! That means stretching ALL of // the (i,i+1) pairs that span the gap! for( int i=0; i