2005 acm icpc taipei problem set

21
2005 ACM Regional Programming Contest Asia Taipei 2005/10/30 There are 9 problems, 21 pages, in this problem set. The team who solves the most number of problems wins the contest. If more than one team solve the same number of problems, then the team who takes less time to solve the problems wins. Each submitted program will be judged to be either correct or incorrect. A correct program must solve all the test cases of the problem correctly. The time to solve a problem is measured from the beginning of the contest to the time the submission of the program which solves the problem correctly, plus a penalty of 20 minutes for each incorrect submission for the problem. There are no penalties for the submitions of the problems which cannot be solved correctly at the end of the contest. Sample input data and the output for the sample input are provided in each problem. You may create these sample input data to test your program. However, test cases used by the Judges may not be the same as the sample input. It is not necessary to include comments in your programs. Any algorithm can be used to solve the problems. However, a program whose running time exceeds 30 seconds will be considered to be incorrect. Each input file may contain more than one test case. The description of the input format is based on records. A record usually contains a list of data. Unless stated otherwise, these data may span more than one line. The number of characters in a line is no more than 255. A special record, usually one or more 0’s, indicates the end of an input data. Anything after this special record should be ignored. The name of the input file for problem i is pi.in. Error checking of the input data is not required. You may assume that the input data are always correct. The output file must be the standard output, unless it is specified in the problem. 1

Upload: aligfaisal

Post on 28-Apr-2015

59 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: 2005 ACM ICPC Taipei Problem Set

2005 ACM Regional Programming Contest

Asia Taipei

2005/10/30

There are 9 problems, 21 pages, in this problem set. The team who solves the most numberof problems wins the contest. If more than one team solve the same number of problems, thenthe team who takes less time to solve the problems wins.

Each submitted program will be judged to be either correct or incorrect. A correctprogram must solve all the test cases of the problem correctly. The time to solve a problem ismeasured from the beginning of the contest to the time the submission of the program whichsolves the problem correctly, plus a penalty of 20 minutes for each incorrect submission for theproblem. There are no penalties for the submitions of the problems which cannot be solvedcorrectly at the end of the contest.

Sample input data and the output for the sample input are provided in each problem. Youmay create these sample input data to test your program. However, test cases used by theJudges may not be the same as the sample input.

It is not necessary to include comments in your programs. Any algorithm can be usedto solve the problems. However, a program whose running time exceeds 30 seconds will beconsidered to be incorrect.

Each input file may contain more than one test case. The description of the input formatis based on records. A record usually contains a list of data. Unless stated otherwise, thesedata may span more than one line. The number of characters in a line is no more than 255. Aspecial record, usually one or more 0’s, indicates the end of an input data. Anything after thisspecial record should be ignored.

The name of the input file for problem i is pi.in. Error checking of the input data is notrequired. You may assume that the input data are always correct. The output file must be thestandard output, unless it is specified in the problem.

1

Page 2: 2005 ACM ICPC Taipei Problem Set

Problem 1Numbering Cities

Input file: p1.in

Scientists and engineers have found a way for human to settle in a far-away planet. Thenew immigrants have started building small towns and communication links connecting nearbytowns. In building the communication network, they first chose a town as a center. Then theyconnected each nearby town to the center by a communication link.

As more and more people migrate to the new planet, a number of such networks have beenbuilt. These networks need to be connected to make it possible for people in every town inthe planet to communicate. They connected these networks by connecting the centers using asimple path.

The first group of immigrants are mostly scientists and engineers. They prefer numberingtheir towns rather than naming them. Consider n towns connected by a network with only onecenter. If we number the center 0 and the nearby towns by integers in {1, 2, . . . , n − 1}. Thereis an interesting property of this numbering method. Suppose that we label of each link by theabsolute value of the difference of the numbers of the two towns it connects. All links will get adistinct label. Furthermore, the labels of the links are exactly {1, 2, . . . , n− 1}. Thus, links arenumbered automatically. This is called perfect numbering of the towns.

The immigrants love the numbering method very much, and wants to know if the numberingcan be extended to the networks with many centers. Therefore, you are invited to write aprogram to solve the problem.

Let us study more about perfect numbering of the towns. Assume that all towns areproperly numbered. It is easy to see that if the numbers of any two towns connected to thesame center are switched, then the new numbering is also perfect. Therefore, perfect numberingof the towns is not unique.

It is convenient to assign a name to each town. Assume that there are at most 26 centers,and they are labeled by a0, b0 . . . , z0. The towns connected to center a0 will be called a1, a2, . . .,the towns connected to center b0 will be called b1, b2, . . ., and so on.

To make the problem simple, we want a perfect numbering such that the numbers assign tothe towns connected to the same center are ordered by their names. For example, ai’s label willbe smaller than aj’s label whenever i < j. Finally, it is required to label a0 with 0 wheneverpossible.

Input FormatThe input file contains several test cases. Each test case is described in 2 lines. The first line

is an integer n, which is the number of centers. The second line contains n integers. Each integerindicates the number of nearby towns connected to the corresponding center. For example,

4

3 2 2 4

means that there are 4 centers a0, b0, c0, and d0. The center a0 connects 3 nearby towns, thecenter b0 connects 2 nearby towns, etc.

Assume that each center can connect at most 60 towns.The last test case is followed by a 0, which signals the end of input file.

2

Page 3: 2005 ACM ICPC Taipei Problem Set

Output FormatFor each test case print out the labels of each town. The output should be ordered by

labels, not by the names of the towns. Print 8 (town, label) pairs in a line, except the last line.Print 1 blank line in front of each test case. If there are no solutions, print “no solutions”.

Sample Input

4

3 2 2 4

5

0 0 0 0 0

0

Output for the Sample Input

(a0, 0) (b1, 1) (b2, 2) (c0, 3) (d1, 4) (d2, 5) (d3, 6) (d4, 7)

(d0, 8) (c1, 9) (c2, 10) (b0, 11) (a1, 12) (a2, 13) (a3, 14)

(a0, 0) (c0, 1) (e0, 2) (d0, 3) (b0, 4)

3

Page 4: 2005 ACM ICPC Taipei Problem Set

Problem 2Perfect Domination on Trees

Input file: p2.in

The concept of domination in graph theory arises naturally from the facility location prob-lem in operations research. Consider a geographical area that is partitioned into regions. Facili-ties are going to be placed in some of the regions. The problem is to choose a minimum numberof regions at which to place these service facilities, so that each region is served by a facility init or at least one facility adjacent to it when there is no facility in this region. This locationproblem can be modeled by a graph problem to find a minimum-cardinality vertex subset ofan input graph such that every vertex not in the subset is adjacent to at least one vertex inthe subset. Depending on different requirements in various location problems, domination hasmany variants. Here we consider one of the variants.

A perfect dominating set of a graph G = (V, E) is a subset D ⊆ V such that every vertexv in V − D (that is, v ∈ V and v /∈ D) is adjacent to exactly one vertex in D. The perfect

domination problem is to find a minimum-cardinality perfect dominating set D of G, i.e., |D|is smallest among the cardinalities of all perfect dominating sets of G. The perfect domination

number of a graph G, denoted by perfect(G), is the cardinality of a minimum-cardinality perfectdominating set of G. In this problem, you need to write a program to find the perfect dominationnumber of an input graph which is a tree.

For example, consider a 6-vertex tree T shown in Figure 1. In (a), vertices 3 and 5 do notform a perfect dominating set of T , because vertex 6 is not in D = {3, 5} and it is not adjacentto any vertex in D. Furthermore, vertices 4 is adjacent to both vertex 3 and 5. In (b), vertices 3and 4 form a perfect dominating set. It is also easy to check that {3, 4} is a minimum-cardinalityperfect dominating set of T . Therefore, the perfect domination number of this example equals2.

Figure 1: An illustration of a none perfect dominating set and a perfect dominating set

In this problem, the input graph is a tree T with n vertices {1, 2, . . . , n}, where 1 ≤ n ≤1000. Write a program to compute the perfect domination number of T .

4

Page 5: 2005 ACM ICPC Taipei Problem Set

Input FormatThe input consists of a number of test cases. Each test case consists of one tree, which has

the following format: The first line contains one positive integer m = n−1, which is the numberof edges of the tree. The next m lines contain m edges such that one line contains one edge.Each edge is represented by two positive integers; the first integer represents one end-vertexof the edge and the second one represents the other end-vertex. Finally, a 0 at the last lineindicates the end of the input file.

Output FormatThe output contains one line for each test case. Each line contains an integer, which is the

perfect domination number of the corresponding input tree.

Sample Input

5

1 3

2 3

3 4

4 5

4 6

1

1 2

0

Output for the Sample Input

2

1

5

Page 6: 2005 ACM ICPC Taipei Problem Set

Problem 3Dome of Tuxville

Input file: p3.in

It has been many years since the MacroSolved Cybercomputer has taken control of earthand enslaved most of the humanity to power its operation through some biological process withan enormous matrix of cells each containing a paralyzed human prison. Now, even the city ofTuxville, the only know remaining habitat where humans can walk freely, is constantly raidedand bombarded by fleets of giant flying robotic bugs sent by MacroSolved.

The engineers in Tuxville has recently developed a new technology called shield projectorfor protecting the city. The projector is placed on the ground and is fed enough energy so thatit creates a semi-sphere dome of radius R, within which no robotic bugs can enter. Of coursethe required energy is a strictly increasing function of R. The city council has requested theengineers to find the best spot to place the shield projector, so that it requires the minimalamount of energy while generating a dome of shield large enough to protect every building inthe city. As a junior member of the engineering team, you are to compute the desired position(the x-y coordinates) for the projector given the list of positions and heights of all buildings inTuxville.

Input FormatThe input file consists of several test cases. Each test case begins with an integer N ,

1 ≤ N ≤ 30, the number of buildings in Tuxville. Each of the next N lines contains 3 realnumbers x, y, and h which gives the position and the height of one building. The last test caseis followed by a line consisting of a single 0.

Every real number t in the input file has at most 3 digits after the decimal point and−999.999 ≤ t ≤ 999.999.

Note that there may be two or more buildings of equal or different heights occupying thesame position, such as buildings 3 and 5 in the second test case. There may also be three ormore buildings lying on the same straight line as exemplified by buildings 1, 2, and 4 in thesecond test case.

Output FormatPrint the x-y coordinates of the desired position for each test case on one line. Round all

numbers to 3 decimal places, printing the trailing 0’s after the decimal place as necessary.

6

Page 7: 2005 ACM ICPC Taipei Problem Set

Sample Input

4

2.0 1.0 0.2

1.0 -2.0 0.3

-0.2 1.3 7.9

-2.0 1.0 0.1

5

1.0 8.0 4.0

8.0 -4.0 1.0

-4.0 1.0 8.0

4.5 2.0 2.0

-4.0 1.0 3.0

0

Output for the Sample Input

-0.200 1.300

0.000 0.000

7

Page 8: 2005 ACM ICPC Taipei Problem Set

Problem 4Forest Trek

Input file: p4.in

Captain Picard and the Enterprise crew is under a mission to study an interesting culturein a distant planet called Ba’ku. They decide to build an invisible observation station wherethey can watch and record how Ba’ku people live, without revealing the crew’s presence or inany way disturbing the Ba’ku people.

The Ba’ku people live on a continent almost fully covered by the trees and completelysurrounded by the ocean. There are populated villages, connected by trails. The trail systemcovers the entire continent and divides the continent into many forests. It is one of these foreststhat Picard and his crew will choose to build the station in. According to past experience andsome correlation study, the level of exploration by the inhabitants is directly proportional to thecollective population of the surrounding villages, and inversely proportional to the area of theforest. Please help Picard find the forest which is least explored by the Ba’ku inhabitants.

Input FormatThe input file consists of several test cases. Each test case begins with a integer V , 3 ≤ V ≤

100, the number of villages on the continent. Each of the next V lines contains 4 entries separatedby spaces—the village name, the village population, and its position in x-y coordinates. Thenext line contains an integer E, 3 ≤ E ≤ 4950, the number of trails connecting villages. Eachof the next E lines contains 2 village names separated by spaces. The last test case is followedby a line consisting of a single 0.

Every real number t in the input file has at most 3 digits after the decimal point and−999.999 ≤ t ≤ 999.999. The names of the villages are in all capitals, and the length of a nameis between 1 and 8, inclusive.

The villages and the trails do not appear in any particular order in the input file. A trailbetween two villages, say ”ALF” and ”BET”, will appear only once, either as ”ALF BET” oras ”BET ALF”. Trails do not meet each other except at the villages. Every village is directlyor indirectly connected to every other village.

In computing the area of the forests, the trails are considered as straight line segments,and neither trails nor villages occupy significant areas. Assume that the outer rim of the trailsystem is built along the coast line.

8

Page 9: 2005 ACM ICPC Taipei Problem Set

Output FormatFor each test case, print on one line the smallest population density rounded to 3 decimal

places, along with the desired forest denoted by its surrounding villages. For the population,print the trailing 0’s after the decimal place as necessary. For the village names, print them incounter-clockwise order. Suppose the desired forest is surrounded by k villages. Of all k possibleoutput sequences, print the one beginning with the alphabetically first village. If there are morethan one such sequences, print the one whose second city has the smallest alphabetical ordering.Thus we choose ”ALF BET ...” over ”ALF EPS ...” in the sample output.

-3

-2

-1

0

1

2

3

-4 -3 -2 -1 0 1 2 3

500:ALF

400:BET

500:CALM 400:DEL 600:EPS 500:FIE 500:GO 400:HUA

500:ING

In the sample input there are three forests. We find their surrounding populations, areas,and densities to be the following, and therefore output information describing the second forest.Note that each of ALF and BET only contributes once to the collective population of the secondforest.

population area density2000 2.000 1000.0003400 5.500 618.1821400 0.500 2800.000

9

Page 10: 2005 ACM ICPC Taipei Problem Set

Sample Input

9

ALF 500 0.000 2.000

BET 400 0.000 1.000

CALM 500 -3.000 0.000

DEL 400 -2.000 0.000

EPS 600 -1.000 0.000

FIE 500 0.000 0.000

GO 500 1.000 0.000

HUA 400 2.000 0.000

ING 500 0.000 -2.000

11

DEL CALM

ING DEL

ING HUA

ING EPS

ALF DEL

ALF HUA

ALF EPS

ALF BET

BET FIE

BET GO

FIE GO

0

Output for the Sample Input

618.182 ALF BET GO FIE BET ALF EPS ING HUA

10

Page 11: 2005 ACM ICPC Taipei Problem Set

Problem 5Real-Time Disk Scheduling

Input file: p5.in

A magnetic disk is made up of the rotating disks, the heads to access disks, and an assemblyarm that moves the heads into the specified cylinder. Generally, a disk task would specify thetrack location of data we want to retrieve. When serving the disk task, a seek-time is taken tomove the disk arm to the appropriate cylinder. The seek-time to move the disk arm from tracklocation x to track location y is b|x − y|. Here b is a given constant, representing the speed ofthe disk, |x − y| is the distance (absolute value) between x and y.

Conventionally, the goal of disk scheduling is to maximize the disk-throughput for servinga given set of tasks. That is, all tasks must be scheduled and executed as soon as possibleto minimize the execution time. However, in a time-critical application, the first goal of diskscheduling is to meet the specified real-time constraints. That is, all tasks must be finished beforeits deadlines. Maximizing the disk throughput is also important, but the schedule is meaninglessif the specified real-time constraints are not satisfied. Therefore, the formal definition of thereal-time disk scheduling is as follows:

Given a set of real-time disk tasks T = {T1, T2, . . . , Tn}, where n is the number ofinput disk tasks. Each task has a deadline and a track location. We say that aschedule is feasible if all tasks meet their deadlines in the schedule. Our goal is tofind a feasible schedule with minimum execution time.

For example, assume that we have four tasks,

{T1, T2, T3, T4}

whose deadlines are{5, 10, 12, 24}

and track locations at{100, 40, 600, 70}.

Assume that the current position of disk head is 20 and b = 0.01. The optimal solution is(2, 4, 1, 3). That is, the tasks are scheduled in the order:

T2, T4, T1, T3.

The minimum execution time for the schedule of this four tasks are

0.01(40 − 20) + 0.01(70 − 40) + 0.01(100 − 70) + 0.01(600− 100) = 5.8.

In this schedule, all tasks are scheduled before their deadlines. Note that the disk headcan be at any position before the schedule starts, and can be at any position when the scheduleends.

11

Page 12: 2005 ACM ICPC Taipei Problem Set

Input FormatThe input file may contain several test cases. Each test case consists of a set of real-time

disk tasks. The first line of test case is a single integer n, representing the number of tasks. Thesecond line of the test case has two numbers. The first number is a real number, representingthe disk speed b. The second number is an integer p, representing the current position of diskhead. Starting from the third line, each line specifies a task. There are two integers in each line.The first integer is the track location of the task. The second integer is the deadline of the task.All integers have the maximum value 1000000.

The last test case is followed by a line containing 0. This signals the end of the input file.

Output FormatThe output is a number t, the minimum execution time of all tasks. If no feasible schedules

exist, output -1.

Sample Input

4

0.01 20

100 5

40 10

600 12

70 24

0

Output for the Sample Input

5.8

12

Page 13: 2005 ACM ICPC Taipei Problem Set

Problem 6Verifying Experimental Data

Input file: p6.in

Professor Abscentmind collects n, 1 ≤ n ≤ 1000, rocks during a field trip. His mission is toanalyze the relations between the weights of the rocks. Unfortunately, the car carries ProfessorAbscentmind had an accident. In the accident, all of his scales were broken. The rocks are heavyand cannot be carried back. He can only hand design a balance that can only tell whether onerock is heavier than the other or not, and performs the experiments on the field. ProfessorAbscentmind can only put one rock on one end of the balance and one other rock on the otherend of the balance. There is no way to put multiple rocks or no rocks on one end of the balance.

Because the balance is hand made without fine tuning, it cannot tell whether two rocksare equal weight or not even if they are. Furthermore, when the weights of the two rocks areclose, the balance may have a measurement error. That is, the balance may say rock 1 is heavierthan rock 2 while actually rock 1 is lighter than rock 2. Professor Abscentmind marked therocks from 1 to n and recorded the results of the balancing experiments. After he had used thebalance m, 1 ≤ m ≤ 10000, times, the balance broke down and could not be repaired.

We call each time the balance is used a measurement. A measurement can be recorded asan ordered pair < i, j >, where i and j are the indices of the two rocks being balanced, and theresult is rock i is heavier than rock j. It is impossible to have a measurement < i, i >. Notethat it is possible that two rocks are balanced more than once with same or different results.Each measurement counts no matter it is a duplicate or not.

After Professor Abscentmind returns to the laboratory, he wants to verify the correctnessof his experimental data. He knows that if rock a1 is heavier than rock a2, and rock a2 is heavierthan rock a3, then rock a1 must be heavier than rock a3. A measurement < i, j > is suspicious ifthere exists a sequence of measurements H =< j, b1 >, < b1, b2 >, < b2, b3 >, . . ., < bk−1, bk >,< bk, i > where k > 0. That is, the balance says i is heavier than j, but you can deduce thecontradictory result of j is heavier than i by a sequence of measurements H or there is anothermeasurement H =< j, i >.

Your task is to write a program to determine the number of suspicious measurements,counting all possible duplicates, giving a set of experimental records.

Input FormatThe input file may contain more than one set of experimental records. The first two line of

each experimental record contains n and m respectively. Then follows by m lines, each line hastwo numbers i and j separated by a blank indicating the measurement result < i, j >. The lastset of experimental records is followed by a line containing 0, indicating the end of test file.

Output FormatFor each set of experimental records, output the number of suspicious measurements.

13

Page 14: 2005 ACM ICPC Taipei Problem Set

Sample Input

3

3

1 2

2 3

3 1

2

1

1 2

0

Output for the Sample Input

3

0

14

Page 15: 2005 ACM ICPC Taipei Problem Set

Problem 7Easy and Not Easy Sudoku Puzzles

Input file: p7.in

Sudoku is popular puzzle demanding logic and patience. The aim of the puzzle is to entera numeral from 1 through 9 in each cell of a 9 × 9 grid made up of 3 × 3 sub-grids, startingwith various numerals given in some cells. Each row, column and sub-grid must contain onlyone instance of each numeral. See Figure 2 and Figure 3 for a sample puzzle and its solution.

5 3 76 1 9 5

9 8 6

8 6 34 8 3 17 2 6

6 2 84 1 9 5

8 7 9

Figure 2: An example of a Sudoku puzzle

5 3 4 6 7 8 9 1 26 7 2 1 9 5 3 4 81 9 8 3 4 2 5 6 7

8 5 9 7 6 1 4 2 34 2 6 8 5 3 7 9 17 1 3 9 2 4 8 5 6

9 6 1 5 3 7 2 8 42 8 7 4 1 9 6 3 53 4 5 2 8 6 1 7 9

Figure 3: A solution to the Sudoku puzzle

Some Sudoku puzzles may have unique solution. Dr. Susie thinks it is a good tool toenhance children’s patience. However, he wants to avoid difficult puzzles so that the childrenwill be able to solve it in a reasonable amount of time. After some research, Dr. Susie noticedthat the following two heuristics are easily understood by children:

1. Each numeral can appear in any row, column, and sub-grid only once. Therefore, if theunion of the numeral appeared in the same row, column and sub-grid of some free cellcontains 8 numerals, and leaves only one available numeral to be filled into that cell, thenit should be filled with that numeral. For example, in Figure 4, the cell marked x canonly be filled with 2 since all the other 8 numerals have appeared in the row, column andsub-grid of it.

15

Page 16: 2005 ACM ICPC Taipei Problem Set

2. Each sub-grid has to contain all the numerals. Therefore, if a numeral has not appearedin some sub-grid, say numeral 1, if there is only one free cell which can be filled by 1, dueto the fact that all the other free cells in that sub-grid have 1 in the same row or column,then fill that cell with numeral 1. For example, in Figure 5 only the cell marked x can befilled with 1, all the other free cells are ruled out for the possibility due to 1s appeared inother sub-grid.

1 6 x 71

4 9

3

5

8

Figure 4: Heuristic Rule 1

1 71

6 x

1

Figure 5: Heuristic Rule 2

He decided that if a puzzle can be solved by only applying the two heuristics above, then itis an easy puzzle, otherwise it is not an easy puzzle. You are to write a program to tell whetherpuzzles are easy or not easy.

Input FormatThe first line contains an integer n, n ≤ 15, indicating the number of puzzles. The following

9n rows contains n puzzles. Each puzzle consists of 9 rows. Each row contains 9 numerals—0indicates that the cell has to be filled, and other numerals indicate that the cell is given thatnumeral.

16

Page 17: 2005 ACM ICPC Taipei Problem Set

Output FormatThe output are n bits. The i-th bit equals to 1 if the i-th puzzle is easy, and 0 if the puzzle

is not easy.

Sample Input

2

0 8 0 3 0 0 0 0 9

0 0 0 0 8 0 0 0 3

3 0 0 5 0 0 0 8 2

1 9 8 4 5 7 3 2 6

5 2 3 9 6 1 8 4 7

4 7 6 2 3 8 1 9 5

9 3 4 8 2 5 7 6 1

6 5 2 0 0 4 9 3 8

8 1 7 6 9 3 2 5 4

7 8 0 3 0 0 0 0 9

0 0 0 0 8 0 0 0 3

3 0 0 5 0 0 0 8 2

1 9 8 4 5 7 3 2 6

5 2 3 9 6 1 8 4 7

4 7 6 2 3 8 1 9 5

9 3 4 8 2 5 7 6 1

6 5 2 0 0 4 9 3 8

8 1 7 6 9 3 2 5 4

Sample output:

01

17

Page 18: 2005 ACM ICPC Taipei Problem Set

Problem 8The Rank of a Tree

Input file: p8.in

Let Bn denote the set of binary trees with n internal nodes (and thus with n + 1 leaves)and T ∈ Bn. We assume that all internal nodes of T are numbered from 1 to n, according tothe in-order traversal of T . For each internal node i ∈ T , the left sub-tree of i is the sub-treeof T rooted at the left child of i. Then the left-weight of i, denoted by wl(T, i), is the numberof leaves in the left sub-tree of i. The integer sequence wl(T ) = (wl(T, 1), wl(T, 2), . . . , wl(T, n))is defined as the left-weight sequence of T and every binary tree can be characterized by itsleft-weight sequence. For example, Figure 6 shows a tree T ∈ B6 with wl(T ) = (1, 2, 1, 4, 1, 2).

T

6

5

4

3

2

1

wl(T ) = (1, 2, 1, 4, 1, 2)

Figure 6: The left-weight sequence of a tree T .

The number of binary trees in Bn is given by the Catalan number

Cn =1

n + 1

(

2n

n

)

.

For example, all the left-weight sequences of T ∈ B4 are listed in Table 1 in lexicographic order.The rank of a left-weight sequence is its ordinal number in the lexicographic order list of allleft-weight sequences in Bn. For example, the rank of the tree T ∈ B4 with wl(T ) = (1, 1, 2, 4)is 7.

Design a program for computing the rank of a specific binary tree T ∈ Bn.

Input FormatThe input file consists of several test cases. Each test case starts with a positive integer n,

3 ≤ n ≤ 10. Then followed by a line which contains the left-weight sequence of a specific binarytree. The line containing a 0 indicates the end of test cases.

Output FormatFor each test case, output the rank of the given left-weight sequence in one line.

18

Page 19: 2005 ACM ICPC Taipei Problem Set

Rank weight sequence1 11112 11123 11134 11145 11216 11237 11248 11319 113410 121111 121212 121413 123114 1234

Table 1: Left-weight sequences of T ∈ B4

Sample Input

5

1 1 1 1 2

8

1 2 3 1 1 2 1 8

10

1 1 2 1 5 1 2 1 4 1

0

Output for the Sample Input

2

1323

9000

19

Page 20: 2005 ACM ICPC Taipei Problem Set

Problem 9Optimal Bus Route Design

Input file: p9.in

A big city wants to improve its bus transportation system. One of the improvement is to addscenic routes which goes through attractive places. Your task is to construct a bus-route-planfor sight-seeing buses in a city.

You are given a set of scenic locations. For each of these given locations, there should beonly one bus route that passes this location, and that bus route should pass this location exactlyonce. The number of bus routes is unlimited. However, each route should contain at least twoscenic locations.

From location i to location j, there may or may not be a connecting street. If there is astreet from location i to location j, then we say j is an out-neighbor of i. The length of thestreet from i to j is d(i, j). The streets might be one way. So it may happen that there is astreet from i to j, but no street from j to i. In case there is a street from i to j and also a streetfrom j to i, the lengths d(i, j) and d(j, i) might be different. The route of each bus must followthe connecting streets and must be a cycle. For example, the route of Bus A might be fromlocation 1 to location 2, from location 2 to location 3, and then from location 3 to location 1.The route of Bus B might be from location 4 to location 5, then from location 5 to location 4.The length of a bus route is the sum of the lengths of the streets in this bus route. The totallength of the bus-route-plan is the sum of the lengths of all the bus routes used in the plan. Abus-route-plan is optimal if it has the minimum total length. You are required to compute thetotal length of an optimal bus-route-plan.

Input FormatThe input file consists of a number of test cases. The first line of each test case is a positive

integer n, which is the number of locations. These n locations are denoted by positive integers1, 2, · · · , n. The next n lines are information about connecting streets between these locations.The i-th line of these n lines consists of an even number of positive integers and a 0 at theend. The first integer is a location j which is an out-neighbor of location i, and the secondinteger is d(i, j). The third integer is another location j′ which is an out-neighbor of i, and thefourth integer is d(i, j′), and so on. In general, the (2k − 1)th integer is a location t which is anout-neighbor of location i, and the 2kth integer is d(i, t).

The next case starts immediately after these n lines. A line consisting of a single 0 indicatesthe end of the input file.

Each test case has at most 99 locations. The length of each street is a positive integer lessthan 100.

Output FormatThe output contains one line for each test case. If the required bus-route-plan exists,

then the output is a positive number, which is the total length of an optimal bus-route-plan.Otherwise, the output is a letter N.

20

Page 21: 2005 ACM ICPC Taipei Problem Set

Sample Input

3

2 2 3 1 0

1 1 3 2 0

1 3 2 7 0

8

2 3 3 1 0

3 3 1 1 4 4 0

1 2 2 7 0

5 4 6 7 0

4 4 3 9 0

7 4 8 5 0

6 2 5 8 8 1 0

6 6 7 2 0

3

2 1 0

3 1 0

2 1 0

0

Sample Output

7

25

N

21