import java.io.*; import java.util.*; /** * Juggler * @author vanb * * This problem would be simple, except for the size of the numbers. * * Put all of the balls into an array. * Look at the first drop. That's easy - it's just some arithmetic on the indices. * Look at the second - that's the same, except you've got to account for the * first ball dropped. And the third? That's the same, except that you've got to * account for the first AND second balls dropped. That's adding up to an O(n^2) * algorithm and that's too much. * * Suppose we were to rearrange the balls? Suppose we were to take all of the remaining * balls and move them to the head of the array? Then, we're back to just arithmetic * on the indices. The problem is that reordering the array is itself an O(n) operation. * If we do that n times, we're back to O(n^2). * * So, suppose we only rearrange the balls sometimes? for instance, suppose we do it * every, oh, say, sqrt(n) ball drops? * * So, our algorithm resets every sqrt(n) ball drops. Each pass between reordering is * O(sqrt(n)^2) (which is O(n))), and we do it sqrt(n) times, so that comes out to * O(n*sqrt(n)). Now, what about the reordering? That's O(n), and we do it sqrt(n) times, * so that, too, comes out to be O(n*sqrt(n)). So, the whole algorithm comes in at O(n*sqrt(n)). */ public class juggler { public Scanner sc; public PrintStream ps; /** * Do it! * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); //new File( "juggler.in" ) ); ps = System.out; //new PrintStream( new FileOutputStream( "juggler.out" ) ); // Allocate tables beforehand int ballat[] = new int[100000]; int indexof[] = new int[100000]; int idropped[] = new int[100000]; for(;;) { int n = sc.nextInt(); if( n==0 ) break; // Populate ballat[] and indexof[] // ballat[i] is the ball at index i // indexof[b] is the index of ball b for( int i=0; i99 ? (int)Math.sqrt( n ) : 100; // Loop through all of the balls, in order for( int b=0; b0 ) { if( inhand==k ) inhand = j; ballat[j] = ballat[k]; indexof[ballat[j]] = j++; } } // Reset ndropped = 0; remaining -= sqrt; } } ps.println( total ); } } /** * Main * @param args Unused * @throws Exception */ public static void main( String[] args ) throws Exception { new juggler().doit(); } }