import java.io.*; import java.util.*; import java.awt.geom.*; /** * Solution to Uniform Subtrees. * * The 'answer' is a list that looks something like this (for the first Sample Input case): * * 0 * 1 0 * 1 1 0 * 1 1 1 0 * 1 1 2 0 * 1 2 0 * 1 3 0 * 2 0 * 2 1 0 * 2 1 1 0 * * All of these, taken together, can be represented as a tree, with numbers on the edges. * Each list is a path to a node (with a '0' stuck on the end). For example, the tree for this * case would look like this: * * X * / \ * 1 2 * / \ * X X * /|\ | * 1 2 3 1 * / | \ | * X X X X * / \ | * 1 2 1 * / \ | * X X X * * So, the trick is to build this 'Answer Tree' from the input tree. * Then, we just have to do a preorder traversal, print the path to every node, * stick a '0' at the end of each, and we're done. * * @author vanb */ public class uniformsubtrees_vanb { public BufferedReader br; public PrintStream ps; /** * This is a node in the Answer Tree * * @author vanb */ public class AnswerNode { /** This count is the number of siblings that this node appears in */ public int count; /** * Children of this Answer Node, with the integer link. * children[i] is the child of this node from the link labeled 'i'. */ public AnswerNode children[]; /** * Create an empty Answer Node */ public AnswerNode() { count = 0; children = new AnswerNode[1]; } /** * Show the answers from this node down. * * @param prefix Part of the answer generated by ancestors */ public void showAnswers( String prefix ) { ps.println( prefix + "0" ); for( int i=1; i children = new LinkedList(); /** * Build the Answer Tree for this node. * * @return Root of the Answer Tree */ public AnswerNode buildAnswerTree() { AnswerNode root = null; for(TreeNode child : children ) { root = merge( root, child.buildAnswerTree() ); } AnswerNode result = new AnswerNode(); if( root!=null ) { result.children = new AnswerNode[root.count+1]; for( int i=1; i<=root.count; i++ ) { result.children[i] = root.copy(i); } } return result; } /** * Convert the subtree rooted at this node into a pretty string. * This is useful for debugging, and also for the judges creating data. */ public String toString() { String result = "("; for( TreeNode child : children ) { result += child.toString(); } result += ")"; return result; } } /** Input text, which will be parsed into a tree. */ public char text[]; /** Pointer into the input text. */ public int p; /** * Parse a single node of the input tree. * @return Parsed node */ public TreeNode parseNode() { TreeNode treeNode = new TreeNode(); if( text[p]!='(' ) System.err.println( "PANIC! Expecting '(' got '" + text[p] + "'"); ++p; // Go past the '(' while( p