37th ICPC

ICPC 2013

Saint Petersburg, Russia · 11 problems

View standings
Top of the standings
  1. 1St. Petersburg National Research University of IT, Mechanics and Optics · SPb NRU ITMO 1Gennady Korotkevich, Mikhail Kever, Niyaz Nigmatullin10
  2. 2Shanghai Jiao Tong University · MithrilBin Jin, Jingbo Shang, Xiaoxu Guo9
  3. 3The University of Tokyo · University of AgitsuneKensuke Imanishi, Makoto Soejima, Yui Hosaka8

Problems

11 problems
  1. Problem A · Self-Assembly

    Time Limit: 3 seconds

    Automatic Chemical Manufacturing is experimenting with a process called self-assembly. In this pro- cess, molecules with natural affinity for each other are mixed together in a solution and allowed to spon- taneously assemble themselves into larger structures. But there is one problem: sometimes molecules assemble themselves into a structure of unbounded size, which gums up the machinery.

    You must write a program to decide whether a given collection of molecules can be assembled into a structure of unbounded size. You should make two simplifying assumptions: 1) the problem is restricted to two dimensions, and 2) each molecule in the collection is represented as a square. The four edges of the square represent the surfaces on which the molecule can connect to other compatible molecules.

    In each test case, you will be given a set of molecule descriptions. Each type of molecule is described by four two-character connector labels that indicate how its edges can connect to the edges of other molecules. There are two types of connector labels:

    • \bullet An uppercase letter (A,...,ZA, . . . , Z) followed by ++ or -. Two edges are compatible if their labels have the same letter but different signs. For example, A+A+ is compatible with AA-but is not compatible with A+A+ or BB-.

    • \bullet Two zero digits 0000. An edge with this label is not compatible with any edge (not even with another edge labeled 0000).

    Assume there is an unlimited supply of molecules of each type, which may be rotated and reflected. As the molecules assemble themselves into larger structures, the edges of two molecules may be adjacent to each other only if they are compatible. It is permitted for an edge, regardless of its connector label, to be connected to nothing (no adjacent molecule on that edge).

    Figure A.1 shows an example of three molecule types and a structure of bounded size that can be assem- bled from them (other bounded structures are also possible with this set of molecules).

    Figure A.1: Illustration of Sample Input 1.

    Figure A.1: Illustration of Sample Input 1.

    ACM-ICPC World Finals 2013 Problem A: Self-Assembly

    Input

    The input consists of a single test case. A test case consists of two lines. The first contains an integer nn (1n400001 \le n \le 40 000) indicating the number of molecule types. The second line contains nn eight-character strings, each describing a single type of molecule, separated by single spaces. Each string consists of four two-character connector labels representing the four edges of the molecule in clockwise order.

    Output

    Display the word unbounded if the set of molecule types can generate a structure of unbounded size. Otherwise, display the word bounded.

    Sample Input 1

    3
    A+00A+A+ 00B+D+A- B-C+00C+
    

    Sample Output 1

    bounded
    

    Sample Input 2

    1
    K+K-Q+Q-
    

    Sample Output 2

    unbounded
    

    ACM-ICPC World Finals 2013 Problem A: Self-Assembly

  2. Problem B · Hey, Better Bettor

    Time Limit: 4 seconds

    “In the casino, the cardinal rule is to keep them playing and to keep them coming back. The longer they play, the more they lose, and in the end, we get it all.”

    (from the 1995 film Casino)

    Recent recessions have not been kind to entertainment venues, including the gambling industry. Com- petition is fierce among casinos to attract players with lots of money, and some have begun to offer especially sweet deals. One casino is offering the following: you can gamble as much as you want at the casino. After you are finished, if you are down by any amount from when you started, the casino will refund x%x\% of your losses to you. Obviously, if you are ahead, you can keep all of your winnings. There is no time limit or money limit on this offer, but you can redeem it only once.

    For simplicity, assume all bets cost 1 dollar and pay out 2 dollars. Now suppose xx is 20. If you make 10 bets in total before quitting and only 3 of them pay out, your total loss is 3.2 dollars. If 6 of them pay out, you have gained 2 dollars.

    Given xx and the percentage probability pp of winning any individual bet, write a program to determine the maximum expected profit you can make from betting at this casino, using any gambling strategy.

    Input

    The input consists of a single test case. A test case consists of the refund percentage xx (0x<1000 \le x < 100) followed by the winning probability percentage pp (0p<500 \le p < 50). Both xx and pp have at most two digits after the decimal point.

    Output

    Display the maximum expected profit with an absolute error of at most 10310^{- 3}.

    Sample Input 1

    0 49.9
    

    Sample Output 1

    0.0
    

    Sample Input 2

    50 49.85
    

    Sample Output 2

    7.10178453
    

    ACM-ICPC World Finals 2013 Problem B: Hey, Better Bettor

  3. Problem C · Surely You Congest

    Time Limit: 10 seconds

    You are in charge of designing an advanced centralized traffic management system for smart cars. The goal is to use global information to instruct morning commuters, who must drive downtown from the suburbs, how best to get to the city center while avoiding traffic jams.

    Unfortunately, since commuters know the city and are selfish, you cannot simply tell them to travel routes that take longer than normal (otherwise they will just ignore your directions). You can only convince them to change to different routes that are equally fast.

    The city’s network of roads consists of intersections that are connected by bidirectional roads of various travel times. Each commuter starts at some intersection, which may vary from commuter to commuter. All commuters end their journeys at the same place, which is downtown at intersection 1. If two com- muters attempt to start travelling along the same road in the same direction at the same time, there will be congestion; you must avoid this. However, it is fine if two commuters pass through the same intersection simultaneously or if they take the same road starting at different times.

    Determine the maximum number of commuters who can drive downtown without congestion, subject to all commuters starting their journeys at exactly the same time and without any of them taking a

    Figure C.1: Illustration of Sample Input 2.

    Figure C.1: Illustration of Sample Input 2.

    In Figure C.1, cars are shown in their original locations. One car is already downtown. Of the cars at in- tersection 4, one can go along the dotted route through intersection 3, and another along the dashed route through intersection 2. But the remaining two cars cannot reach downtown while avoiding congestion. So a maximum of 3 cars can reach downtown with no congestion.

    Input

    The input consists of a single test case. The first line contains three integers nn, mm, and cc, where nn (1n250001 \le n \le 25 000) is the number of intersections, mm (0m500000 \le m \le 50 000) is the number of roads, and cc (0c10000\le c\le 1 000) is the number of commuters. Each of the next mm lines contains three integers xix_{i}, yiy_{i}, and tit_{i} describing one road, where xix_{i} and yiy_{i} (1xi,yin1\le xi, yi \le n) are the distinct intersections the road connects, and tit_{i} (1ti100001\le ti \le 10 000) is the time it takes to travel along that road in either direction. You may assume

    ACM-ICPC World Finals 2013 Problem C: Surely You Congest that downtown is reachable from every intersection. The last line contains cc integers listing the starting intersections of the commuters.

    Output

    Display the maximum number of commuters who can reach downtown without congestion.

    Sample Input 1

    3 3 2
    1 2 42
    2 3 1
    2 3 1
    2 3
    

    Sample Output 1

    2
    

    Sample Input 2

    4 4 5
    1 2 5
    1 3 4
    4 2 5
    4 3 6
    4 4 4 4 1
    

    Sample Output 2

    3
    

    ACM-ICPC World Finals 2013 Problem C: Surely You Congest

  4. Problem D · Factors

    Time Limit: 2 seconds

    The fundamental theorem of arithmetic states that every integer greater than 1 can be uniquely repre- sented as a product of one or more primes. While unique, several arrangements of the prime factors may be possible. For example:

    10=2510 = 2\cdot 5 20=22520 = 2\cdot 2\cdot 5

    =52= 5\cdot 2 =252= 2\cdot 5\cdot 2

    =522= 5\cdot 2\cdot 2

    Let f(k)f(k) be the number of different arrangements of the prime factors of kk. So f(10)=2f(10) = 2 and f(20)=3f(20) = 3.

    Given a positive number nn, there always exists at least one number kk such that f(k)=nf(k) = n. We want to know the smallest such kk.

    Input

    The input consists of at most 10001 000 test cases, each on a separate line. Each test case is a positive integer n<263n <2^{63}.

    Output

    For each test case, display its number nn and the smallest number k>1k > 1 such that f(k)=nf(k) = n. The numbers in the input are chosen such that k<263k <2^{63}.

    Sample Input 1

    1
    2
    3
    105
    

    Sample Output 1

    1 2
    2 6
    3 12
    105 720
    

    ACM-ICPC World Finals 2013 Problem D: Factors

  5. Problem E · Harvard

    Time Limit: 10 seconds

    Picture from Wikimedia Commons The term “Harvard architecture” applies to a computer that has physically separate memories for instructions and data. The term originated with the Harvard Mark I computer, delivered by IBM in 1944, which used paper tape for instruc- tions and relays for data.

    Some modern microcontrollers use the Harvard architecture – but not paper tape and relays! Data memory is organized in banks, each con- taining the same number of data items. Each data-referencing instruction has a byte offset ff to a bank, and a bit aa that is used to select the bank to be referenced. If aa is 00, then bank 00 is referenced. If aa is 11, then the value in a bank select register (BSR) identifies the bank to be used. Assume each instruction takes the same time to execute, and there is an instruction that can set the BSR’s value.

    For example, suppose there are 44 banks of 88 bytes each. To access location 55, either use a single instruction with a=0a= 0 and f=5f = 5, or set the BSR to 00 in one instruction and then use an instruction with a=1a= 1 and f=5f = 5. The first approach is faster since it does not require setting the BSR.

    Now suppose (with the same memory) the location to access is 2020. Only one approach will work here: execute an instruction that sets the BSR to 22 (unless the BSR already has the value 22) and then use an instruction with a=1a= 1 and f=4f = 4.

    A program is a sequence of operations. Each operation is either

    • \bullet a variable reference, written as Vii, where ii is a positive integer, or

    • \bullet a repetition, written as Rnn <program> E, where nn is a positive integer and <program> is an arbitrary program. This operation is equivalent to nn sequential occurrences of <program>.

    Your problem is to determine the minimum running time of programs. In particular, given the number and size of the memory banks and a program to be executed, find the minimum number of instructions (which reference memory location and possibly set the BSR) that must be executed to run the program. To do this you must identify a mapping of variables to memory banks that yields the smallest execution time, and report that execution time – that is, the number of memory references and BSR register settings required. The BSR’s value is initially undefined, and changes only when an instruction explicitly sets its value.

    ACM-ICPC World Finals 2013 Problem E: Harvard

    Input

    The input consists of a single test case. A test case consists of two lines. The first line contains two integers bb and ss, where 1b131 \le b \le 13 is the number of memory banks and 1s131 \le s \le 13 is the number of variables that can be stored in each memory bank. The second line contains a non-empty program with at most 10001 000 space-separated elements (each Rnn, Vii, and E counts as one element).

    You may assume the following:

    • \bullet In a repetition Rnn, the number of repetitions satisfies 1n1061\le n\le 10^{6}.

    • \bullet In a loop operation Rnn <program> E, the loop body <program> is not empty.

    • \bullet In a variable reference Vii, the variable index satisfies 1imin(bs,13)1\le i\le min(b\cdot s,13).

    • \bullet The total number of variable references performed by an execution of the program is at most 101210^{12}.

    Output

    Display the minimum number of instructions that must be executed to complete the program.

    Sample Input 1

    1 2
    V1 V2 V1 V1 V2
    

    Sample Output 1

    5
    

    Sample Input 2

    2 1
    V1 V2 V1 V1 V2
    

    Sample Output 2

    6
    

    Sample Input 3

    1 2
    R10 V1 V2 V1 E
    

    Sample Output 3

    30
    

    Sample Input 4

    4 1
    V1 R2 V2 V4 R2 V1 E V3 E
    

    Sample Output 4

    17
    

    ACM-ICPC World Finals 2013 Problem E: Harvard

  6. Problem F · Low Power

    Time Limit: 4 seconds

    You are building advanced chips for machines. Making the chips is easy, but the power supply turns out to be an issue since the available batteries have varied power outputs.

    Consider the problem of nn machines, each with two chips, where each chip is powered by kk batteries. Surprisingly, it does not matter how much power each chip gets, but a machine works best when its two chips have power outputs as close as possible. The power output of a chip is simply the smallest power output of its kk batteries.

    You have a stockpile of 2nk2nk batteries that you want to assign to the chips. It might not be possible to allocate the batteries so that in every machine both chips have equal power outputs, but you want to allocate them so that the differences are as small as possible. To be precise, you want to tell your customers that in all machines the difference of power outputs of the two chips is at most dd, and you want to make dd as small as possible. To do this you must determine an optimal allocation of the batteries to the machines.

    Consider Sample Input 1. There are 22 machines, each requiring 33 batteries per chip, and a supply of batteries with power outputs 1,2,3,4,5,6,7,8,9,10,11,121,2,3,4,5,6,7,8,9,10,11,12. You can, for instance, assign the batteries with power outputs 1,3,51,3,5 to one chip, those with power 2,4,122,4,12 to the other chip of the same machine, those with power 6,8,96,8,9 to the third chip, and those with power 7,10,117,10,11 to the fourth. The power outputs of the chips are 1,2,61,2,6, and 77, respectively, and the difference between power outputs is 11 in both machines. Note that there are many other ways to achieve this result.

    Input

    The input consists of a single test case. A test case consists of two lines. The first line contains two positive integers: the number of machines nn and the number of batteries per chip kk (2nk1062nk \le 10^{6}). The second line contains 2nk2nk integers pip_{i} specifying the power outputs of the batteries (1pi1091\le pi \le 10^{9}).

    Output

    Display the smallest number dd such that you can allocate the batteries so that the difference of power outputs of the two chips in each machine is at most dd.

    Sample Input 1

    2 3
    1 2 3 4 5 6 7 8 9 10 11 12
    

    Sample Output 1

    1
    

    Sample Input 2

    2 2
    3 1 3 3 3 3 3 3
    

    Sample Output 2

    2
    

    ACM-ICPC World Finals 2013 Problem F: Low Power

  7. Problem G · Map Tiles

    Time Limit: 20 seconds

    Publishing maps is not an easy task. First you need some appropriate transformation to display the earth’s spherical shape in a two-dimensional plane. Then another issue arises – most high-quality maps are too large to be printed on a single page of paper. To cope with that, map publishers often split maps into several rectangular tiles, and print each tile on one page. In this problem, you will examine this “tiling” process.

    The International Cartographic Publishing Company (ICPC) needs to cut their printing costs by mini- mizing the number of tiles used for their maps. Even with a fixed tile size (determined by the page size) and map scale, you can still optimize the situation by adjusting the tile grid.

    The left side of Figure G.1 shows 14 map tiles covering a region. The right side shows how you can cover the same region with only 10 tiles, without changing the tile sizes or orientation.

    Figure G.1: Two possible ways of tiling Texas.

    Figure G.1: Two possible ways of tiling Texas.

    Your task is to help the ICPC find the minimum number of tiles needed to cover a given region. For simplicity, the region will be given as a closed polygon that does not intersect itself.

    Note that the tiles must be part of a rectangular grid aligned with the xx-axis and yy-axis. That is, they touch each other only with their whole sides and cannot be rotated. Also note that although all input coordinates are integers, tiles may be located at non-integer coordinates.

    The polygon may touch the edges of marginal lines (as in Sample Input 2). However, to avoid floating- point issues, you may assume the optimal answer will not change even if the polygon is allowed to go outside the map tiles by a distance of 10610^{- 6}.

    Input

    The input consists of a single test case. The first line of a test case contains three integers: nn, xsx_{s}, and ysy_{s}. The number of polygon vertices is nn (3n503\le n\le 50), and xsx_{s} and ysy_{s} (1xs,ys1001\le xs, ys \le 100) are the dimensions of each tile. Each of the next nn lines contains two integers xx and yy (0x10xs0 \le x \le 10x_{s}, 0y10ys0 \le y \le 10y_{s}), specifying the vertices of the polygon representing the region (in either clockwise or counter-clockwise order).

    ACM-ICPC World Finals 2013 Problem G: Map Tiles

    Output

    Display the minimal number of tiles necessary to cover the whole interior of the polygon.

    Sample Input 1

    12 9 9
    1 8
    1 16
    6 16
    9 29
    19 31
    23 24
    30 23
    29 18
    20 12
    22 8
    14 0
    14 8
    

    Sample Output 1

    10
    

    Sample Input 2

    4 5 7
    10 10
    15 10
    15 17
    10 17
    

    Sample Output 2

    1
    

    ACM-ICPC World Finals 2013 Problem G: Map Tiles

  8. Problem H · Matrxka

    Time Limit: 5 seconds

    Matryoshkas are sets of traditional Russian wooden dolls of decreasing size placed one inside the other. A matryoshka doll can be opened to reveal a smaller figure of the same sort inside, which has, in turn, another figure inside, and so on.

    Picture from Wikimedia Commons The Russian Matryoshka Museum recently exhibited a col- lection of similarly designed matryoshka sets, differing only in the number of nested dolls in each set. Unfor- tunately, some over-zealous (and obviously unsupervised) children separated these sets, placing all the individual dolls in a row. There are nn dolls in the row, each with an integer size. You need to reassemble the matryoshka sets, knowing neither the number of sets nor the number of dolls in each set. You know only that every complete set consists of dolls with consecutive sizes from 11 to some number mm, which may vary between the different sets.

    When reassembling the sets, you must follow these rules:

    • \bullet You can put a doll or a nested group of dolls only inside a larger doll.

    • \bullet You can combine two groups of dolls only if they are adjacent in the row.

    • \bullet Once a doll becomes a member of a group, it cannot be transferred to another group or per- manently separated from the group. It can be temporarily separated only when combining two groups.

    Your time is valuable, and you want to do this reassembly process as quickly as possible. The only time-consuming part of this task is opening and subsequently closing a doll, so you want to minimize how often you do this. For example, the minimum number of openings (and subsequent closings) when combining group [1, 2, 6] with the group [4] is two, since you have to open the dolls with sizes 6 and 4. When combining group [1, 2, 5] with the group [3, 4], you need to perform three openings.

    Write a program to calculate the minimum number of openings required to combine all disassembled matryoshka sets.

    Input

    The input consists of a single test case. A test case consists of two lines. The first line contains one integer nn (1n5001 \le n \le 500) representing the number of individual dolls in the row. The second line contains nn positive integers specifying the sizes of the dolls in the order they appear in the row. Each size is between 11 and 500500 inclusive.

    Output

    Display the minimum number of openings required when reassembling the matryoshka sets. If reassem- bling cannot be done (some of the kids might have been excessively zealous and taken some dolls), display the word impossible.

    ACM-ICPC World Finals 2013 Problem H: Matrxka

    Sample Input 1

    7
    1 2 1 2 4 3 3
    

    Sample Output 1

    impossible
    

    Sample Input 2

    7
    1 2 3 2 4 1 3
    

    Sample Output 2

    7
    

    ACM-ICPC World Finals 2013 Problem H: Matrxka

  9. Problem I · Pirate Chest

    Time Limit: 15 seconds

    Pirate Dick finally had enough of fighting, marauding, theft, and making life miserable for many on the open seas. So he decided to retire, and he found the perfect island to spend the rest of his days on, provided he does not run out of money. He has plenty of gold coins now, and he wants to store them in a chest (he is a pirate after all). Dick can construct a rectangular chest with integer dimensions of any size up to a specified maximum size for the top but with an arbitrary integer height. Now he needs a place to hide the chest. While exploring the island, he found the perfect solution.

    Dick will hide his chest by submerging it in a murky pond. The pond has a rectangular surface, and it completely fills the bottom of a valley that has high vertical rocky walls. Dick surveyed the pond and knows its depth for each of the squares of a Cartesian coordinate grid system placed on the pond surface. When Dick submerges the chest, it will sink as far as possible until it touches the bottom. The top of the chest will remain parallel to the pond’s surface and the chest will be aligned with the grid squares. The water displaced by the submerged chest will raise the level of the pond’s surface (this will occur even if there is no space around the chest for the displaced water to rise). The walls of the valley are high enough that the water can never splash out of the valley. Of course, since the chest must be invisible, its top must be strictly below the surface of the pond. Your job is to find the volume of the largest chest that Pirate Dick can hide this way.

    In Figure I.1, the leftmost image shows a pond, the middle image shows a possible placement of a chest of volume 3, and the rightmost image shows a placement of a chest of volume 4, which is the maximum possible volume. Note that if the second chest were made one unit taller, its top would be visible because it would be at exactly the same height as the surface of the water.

    Figure I.1: Illustration of Sample Input 1.

    Figure I.1: Illustration of Sample Input 1.

    Input

    The input consists of a single test case. A test case starts with a line containing four integers aa, bb, mm, and nn (1a,b,m,n5001 \le a, b, m, n \le 500). The pond’s surface dimensions are m×nm\times n and the maximum size of the top (and bottom) of the chest is a×ba\times b. In addition, aa and bb are small enough that it is not possible to cover the entire pond with a chest with top size a×ba\times b. Each of the remaining mm lines in a test case contains nn integers di,jd_{i,j} specifying the pond’s depth at grid square (i,j)(i, j), where 0di,j1090\le di,j \le 10^{9} for each 1im1\le i\le m and 1jn1\le j \le n.

    ACM-ICPC World Finals 2013 Problem I: Pirate Chest

    Output

    Display the maximum volume of a rectangular chest with integer dimensions (where one of the dimen- sions of the top is bounded by aa and the other is bounded by bb) that can be completely submerged below the surface of the pond. If no chest can be hidden in the pond, display 0.

    Sample Input 1

    3 1 2 3
    2 1 1
    2 2 1
    

    Sample Output 1

    4
    

    Sample Input 2

    4 1 1 5
    2 0 2 2 2
    

    Sample Output 2

    12
    

    Sample Input 3

    2 3 3 5
    2 2 2 2 2
    2 2 2 2 2
    2 2 2 2 2
    

    Sample Output 3

    18
    

    ACM-ICPC World Finals 2013 Problem I: Pirate Chest

  10. Problem J · Pollution Solution

    Time Limit: 1 second

    As an employee of Aqueous Contaminate Management, you must monitor the pollution that gets dumped (sometimes accidentally, sometimes purposefully) into rivers, lakes and oceans. One of your jobs is to measure the impact of the pollution on various ecosystems in the water such as coral reefs, spawning

    Figure J.1: Illustration of Sample Input 1.

    Figure J.1: Illustration of Sample Input 1.

    The model you use in your analysis is illustrated in Figure J.1. The shoreline (the horizontal line in the figure) lies on the xx-axis with the source of the pollution located at the origin (0,0). The spread of the pollution into the water is represented by the semicircle, and the polygon represents the ecosystem of concern. You must determine the area of the ecosystem that is contaminated, represented by the dark blue region in the figure.

    Input

    The input consists of a single test case. A test case starts with a line containing two integers nn and rr, where 3n1003 \le n \le 100 is the number of vertices in the polygon and 1r10001 \le r \le 1 000 is the radius of the pollution field. This is followed by nn lines, each containing two integers xi,yix_{i}, y_{i}, giving the coordinates of the polygon vertices in counter-clockwise order, where 1500xi1500- 1 500\le xi \le 1 500 and 0yi15000\le yi \le 1 500. The polygon does not self-intersect or touch itself. No vertex lies on the circle boundary.

    Output

    Display the area of the polygon that falls within the semicircle centered at the origin with radius rr. Give the result with an absolute error of at most 10310^{- 3}.

    ACM-ICPC World Finals 2013 Problem J: Pollution Solution

    Sample Input 1

    6 10
    -8 2
    8 2
    8 14
    0 14
    0 6
    -8 14
    

    Sample Output 1

    101.576437872
    

    ACM-ICPC World Finals 2013 Problem J: Pollution Solution

  11. Problem K · Up a Tree

    Time Limit: 6 seconds

    Anatoly Cheng McDougal is a typical student in many ways. Whenever possible he tries to cut and paste code instead of writing it from scratch. Unavoidably this approach causes him problems. For example, when he first learned about preorder, inorder and postorder traversals of trees, and was given code for a preorder print of a tree (shown on the left below), he simply cut and pasted the code, then moved the print statement to the correct location and renamed the procedure. However, he forgot to rename the procedure calls inside the code, resulting in the defective inorder print and postorder print code shown below.

    void prePrint(TNode t)
    {
      output(t.value);
      if (t.left != null)
        prePrint(t.left);
      if (t.right != null)
        prePrint(t.right);
    }
                             void inPrint(TNode t)
                             {
                               if (t.left != null)
                                 prePrint(t.left);
                               output(t.value);
                               if (t.right != null)
                                 prePrint(t.right);
                             }
                                                     void postPrint(TNode t)
                                                     {
                                                       if (t.left != null)
                                                         prePrint(t.left);
                                                       if (t.right != null)
                                                         prePrint(t.right);
                                                       output(t.value);
                                                     }
    

    At this point, Anatoly did not behave like a typical student. He actually tested his code! Unfortunately, when the results were not correct, he reverted back to typical student behavior. He panicked and started randomly changing calls in all three procedures, hoping to get things right. Needless to say, the situation became even worse now than when he started.

    Anatoly’s professor tested the code on a random tree of characters. When she looked at the output of his three print routines, she correctly guessed what had happened. However, instead of going directly to his code, she decided to try to reconstruct Anatoly’s code just by observing the output. In order to do this, she correctly made the following assumptions:

    1. The output statement in each print routine is in the correct location (for example, between the two recursive calls in the inPrint routine).

    2. Among the six recursive calls made by the three routines, exactly two calls are to prePrint, exactly two are to inPrint, and exactly two are to postPrint, though potentially in the wrong routines.

    Soon the professor realized that reconstructing Anatoly’s code and the test tree from his output was not a simple task and that the result might be ambiguous. You will have to help her find all possible recon- structions of Anatoly’s code. In addition, for each such reconstruction, you are to find the alphabetically first tree (as described in the output section) giving the observed output.

    Input

    The input consists of a single test case. A test case consists of three strings on three separate lines: the observed output of Anatoly’s prePrint, inPrint and postPrint routines (in that order) on some test tree. Each of these strings consists of nn uppercase letters (4n264 \le n \le 26), with no repeated letters in any string. The test case is guaranteed to have at least one solution.

    ACM-ICPC World Finals 2013 Problem K: Up a Tree

    Output

    Display all possible reconstructions for the test case, ordered as described in the last paragraph below. The output for each reconstruction consists of two parts. The first part is a single line and describes the six calls in Anatoly’s routines: first the two (recursive) calls in Anatoly’s prePrint routine, followed by the calls in his inPrint routine, and finally the calls in his postPrint routine. The calls are described by the words Pre, In, and Post, separated by spaces. For example, if Anatoly’s routines were correct, the resulting output of the first part of the reconstruction would be Pre Pre In In Post Post.

    The second part consists of three lines and describes the first test tree that could have generated the ob- served outputs. The first line is the correct preorder print of the tree, and the second and third lines con- tain the correct inorder and postorder prints, respectively. The first tree is the one with the alphabetically first preorder print. If there are multiple such trees, the first of these is the one with the alphabetically first inorder print.

    Every reconstruction is a sequence of 6 tokens chosen from Pre, In, and Post. The ordering of reconstructions is lexicographic with respect to the following ordering of tokens: Pre < In < Post.

    Sample Input 1

    HFBIGEDCJA
    BIGEDCJFAH
    BIGEDCJFAH
    

    Sample Output 1

    Pre Post In Post In Pre
    HFBJCDEGIA
    BIGEDCJFAH
    IGEDCJBAFH
    

    Sample Input 2

    BNLFAGHPEDOCMJIK
    NLBGAPHCODEIJMKF
    NLFAGHPEDOCMJIKB
    

    Sample Output 2

    In Pre In Post Post Pre
    BLNFKMEHAGPCODIJ
    NLBAGHPEODCMIJKF
    NLGAPHDOCEJIMKFB
    Post Pre In In Post Pre
    BLNFKICPGAHEODMJ
    NLBGAPHCODEIJMKF
    NLAGHPDOECJMIKFB
    

    ACM-ICPC World Finals 2013 Problem K: Up a Tree