import java.io.*; import java.util.*; import java.awt.geom.*; /** * Solution to Nested Palindromes * * Here are some observations. Because of the no-adjacent-digits constraint, * no palindrome or sub-palindrome can be of even length. There must always * be a 'middle' digit. Thus, the only legitimate numbers must be 2^n-1 in length, * same as the number of moves in a Towers of Hanoi puzzle with n disks. * In fact, if you letters the digits by first occurrence, you get a string like this: * abacabadabacaba * which is the same as the disk moves in ToH. Every digit past 'a' is only adjacent to 'a'. * So, for any digits you don't know, there are 9 possibilities: * 'a' can be anything but 0 (since the number cannot have a leading zero), * and everything else can be anything but whatever you chose for 'a'. * * @author vanb */ public class nested_vanb { public Scanner sc; public PrintStream ps; // Thinking of this like Towers of Hanoi, // maxlevel is the number of disks public int maxlevel = 0; // The generators are the digits. // Think of them like labels on ToH disks. public char generators[] = new char[15]; /** * Driver. * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); //new File( "nested.judge" ) ); ps = System.out; //new PrintStream( new FileOutputStream( "nested.solution" ) ); // These are legitimate lengths. // They are powers of 2 minus 1 int legit[] = new int[20]; for( int i=0; i<20; i++ ) { legit[i] = (1<>= 1; level++; } if( level>maxlevel ) maxlevel = level; --level; // Look at the generators. If we don't know it yet, set it. if( generators[level]=='-' || generators[level]=='?' ) generators[level] = digits[i]; // If we have a digit mismatch, we fail. if( generators[level]!=digits[i] ) fail = true; } // Can't have '0' as a leading digit. if( generators[0]=='0' ) fail = true; // If we know the first digit, then check all of the others. if( Character.isDigit( generators[0] )) for( int i=1; i1, then we fail if( need==0 && n!=1 ) fail=true; // If the number has more digits than if( need>0 && need>=1; } // If we don't know this one yet if( generators[g]=='?' ) { // Look at the base 9 number to see what digit to use char ch = base9[p++]; // Skip past the digit at position 0 if( generators[0]<=ch ) ++ch; generators[g] = digits[i] = ch; } else { // If we know what digit this should be, just record it. digits[i] = generators[g]; } } ps.println( fail ? "-1" : new String( digits ) ); } } /** * @param args */ public static void main( String[] args ) throws Exception { new nested_vanb().doit(); } }