31.07.2015 Views

LITHUANIAN OLYMPIADS INFORMATICS

LITHUANIAN OLYMPIADS INFORMATICS

LITHUANIAN OLYMPIADS INFORMATICS

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Valentina DagienėJūratė Skūpienė<strong>LITHUANIAN</strong> <strong>OLYMPIADS</strong>IN<strong>INFORMATICS</strong>Year 1999–2002Translation from Lithuanian byGiedrė GabrėnaitėInstitute of Mathematics and InformaticsVilnius, 2002


UDK 004 (076)Da77Darbas parengtas Matematikos ir informatikos institute© Valentina Dagienė, 2002© Jūratė Skūpienė, 2002© Giedrė Gabrėnaitė, vertimas, 2002


PrefaceLithuanian Informatics Olympiads have been held since 1990. The Olympiadconsists of three stages:1) local stage, in schools,2) regional stage,3) national stage; it consists of two parts: first, performed via electronicmail, second, face-to-face.The national stage is specific: it requires a lot of computers in one place at a time.That’s why it is divided into two parts. Approximately 250 students participate in thefirst part of national stage. The National Committee of the Olympiad fixes the numberof competitors and the locations for the part performed via e-mail as well as the numberof competitors and the location for the second part performed face-to-face. Usually,each year the final part of the Olympiad is organized in different city. About 40-50 students are invited for 3-4 competition days.The National Committee of the Olympiad prepares problem sets for each stageand distributes them to the Local Education-Boards. For the first and second stages,schools may use these problems, may modify them or to prepare their own problems.Two books 1 that embrace the problems and their solutions (in Pascal) of all thestages of the Lithuanian Informatics Olympiad in the period 1990–1999 have beenpublished. The translation of problems to English 2 was also prepared. Here we presentthe translation of problem formulations of the last three Olympiads (1999–2002).We express a sincerely appreciation to Giedrė Gabrėnaitė, a student of VilniusGediminas Technical University for the translation as well as to our colleague AidasŽandaris for the preparation of layout. Also, we would like to thank Jari Koivistofrom Finland for revision of the translation.Tests, results, and solutions are available in the internet:http://aldona.mii.lt/pub/MII/PMS/olimp/http://aldona.mii.lt/pub/pms/olimp/Valentina DAGIENĖ,Dagiene@ktl.mii.ltJūratė SKŪPIENĖJurate@ktl.mii.lt1Valentina Dagienė, Jūratė Skūpienė.Problems of Olympiads in Informatics, Book I: I–VII Olympiadas,1999, 270 p.; Book II: VIII–X Olympiadas, 2001, 288 p. (in Lithuanian)2Valentina Dagienė, Jūratė Skūpienė. Lithuanian Olympiads in Informatics, Institute of Mathematics andInformatics, 2001, 80 p.


4OLYMPIAD XISTAGE IJUNIOR DIVISION173. False Coin (theoretical task). There are 10 coins. It is known that one ofthem is false and it is heavier than the others. You have got scales and using them youcan compare weights of the coins. One plate of the scale can hold several coins.Task. Describe how to find out the false coin. The number of weightings must beminimal.174. Video Records. 240 minute videotape costs 10 litas and 90 centas, and 180minute videotape minutes costs 9 litas and 15 centas. Tomas looked through theweekly TV guide of Baltic television and decided to record n television broadcasts.The duration of the broadcast is known. If needed, any of the broadcasts can bedivided into parts and it can be recorded into one or more videotapes, or severalbroadcasts can be recorded into one videotape. Unfortunately, Tom does not have asingle empty videotape.Task. Write an algorithm to calculate the minimal amount of money (litas andcentas) needed to buy the number of videotapes required to record all the desirablebroadcasts.175. Squares from Bricks. There are given n square bricks. A set of squareshaving thickness of one brick should be made from all the given bricks. Firstly thereis made the largest possible square, then from the remaining bricks the second largestsquare is made and etc.Task. Write a program todivide the given number ofbricks into groups needed tobuild each square. For example,when n 6 75, the resultshould be: 64, 9, 1, 1.64 9 1 1Picture 175.1STAGE ISENIOR DIVISION176. False Coin. a) There are 10 coins. It is known that one of them is false andit is heavier than the others. You have got scales and using them you can compareweights of the coins. One plate of the scale can hold several coins. Describe how tofind out the false coin. The number of weightings must be minimal.


) There are n (n ≥ 2) coins. Write an algorithm to calculate the minimal number ofweightings necessary to find out the false coin under conditions described in part a).177. Get the Number. Between the digits 123456789 (written in ascending order)addition and subtraction signs must be put in so that the value of the expressionwould be equal to n (n ≤ maxlongint).Task. Write a program to solve this task. If there areseveral possible solutions, give all of them. If no solutionsexist, give the appropriate message.For example, if n = 120, one of the possible solutionsshould be:123+4-5+6-7+8-9178. Spiral Message. Write an algorithm to print thegiven sentence in spiral. The spiral should be aligned to theleft side of the screen. The sign “+” should used instead of“space”. The length of the sentence should not exceed 70characters. For example, when the given sentence is“Programos tobulinimas – pats geriausias būdas jąsugadinti.” the result is shown in the picture.STAGE IIiisuaireg+a ss t+som t+ o a ab b P r pū u rog +d l – .a inimas+ ist+ją+sugadinPicture 178.15JUNIOR DIVISION179. The Third Millennium. The third millennium began in 2001, on the 1st ofJanuary; the time was 0 hours 0 minutes and 0 seconds. Assume that Jury run yourprogram in the year 2000.Task. Write a program to calculate the remaining number of days (twenty fourhours make one day), hours (


6word, which is called the key to the cipher. Symbols of text tobe enciphered are grouped. Number of symbols in the groupcoincides with the length of the key. Groups are written oneafter another. There can be fewer letters in the last group. Forexample, there is given the key “mitas” and the text “Sunkupranašauti kaip ateityje atrodys elektroninės knygos.” (see thepicture).Letters of the key are numbered. The letter to go earlier inthe Latin alphabet has a smaller number.The enciphered text is obtained in the following way: thesymbols of the first column are written first, then the symbolsof the second column, and etc:m i t a s3 2 5 1 4S u n k u? p r a na š a u ti ? k a ip ? a t ei t y j e? a t r od y s ? el e k t ro n i n ės ? k n yg o s .Picture 180.1kauatjr6tnn.upš66tayen6oS6aipi6dlosguntieeoerėynrakaytskiksSpace characters are marked with symbol “6” here.Task. Write an algorithm to encipher the given text.Input. The first line of the input file contains the key and the second one the text.The key contains only small Latin letters (lower case) and there are no the sameletters in it. The key contains not more than 7 characters; the length of it does notexceed 50. Text can contain letters, space characters and punctuation marks.Output the enciphered text to the output file.181. Frog Performance. Once plenty of frogs lived in the pond and they were notordinary, they were performing frogs. Each frog managed to jump out of the waterand quack periodically of time specific for that frog. For example, the period of frog’squacking is equal to 5. It means that if the frog quacked during the first minute, it willquack the second time after five minutes, that is during the sixth minute, the third timeit will quack during the eleventh minute and etc.Task. At sunrise all the frogs jumped out of the water and quacked. Write an algorithmto find after how many hours and minutes (


STAGE II7SENIOR DIVISION182. Code of the Safe. It is known that code of the safe lock is a natural numberconsisting of n digits. The remainders are also known:– when dividing the code by 5.– when dividing the code by 7.– when dividing the code by 11.Unfortunately, this information is not enough to determine the code unambiguously.Task. Write an algorithm to calculate how many different numbers could be thecode of the safe’s lock and output the smallest of them.Input. Input data consists of four natural numbers written in one line and separated bya single space characters. The number of digits n (2 ≤ n ≤ 9) of the code is written firstly,then the remainders obtained when dividing the code by 5, by 7 and by 11 are given.183. The Product of Numbers in the Diagonals. Assume an n×n table containsnatural numbers. You should check if the products of the numbers on the main diagonalsof the table are equal. If not, find the largest quadratic table (part of the given table) thatwould satisfy this condition. If there can be several such tables, find any one of them.Note. Table having size 1×1 can also be a solution.Input. The first line of the input file contains the size of table n (2 ≤ n ≤ 8) and theremaining n lines contain the table itself. The table is such that the product of numbersin any diagonal of the table does not exceed maxlongint.Output. The largest quadratic table satisfying the condition or the message PROD-UCTS ARE EQUAL must be written to the output file.Example 1 Example 2Input Output Comments Input Output Comments4 5 6 PRODUCTS 4×3×3 = 2 1 1 2 1 2×1×3=6≠1 3 2 ARE 6×3×2 2 1 4 2 1 1=1×1×12 7 3 EQUAL 1 7 3 2×1=2×1184. Koch’s Quadric Island. Koch’s quadric island of the first degree containsquadrate (pict. 184.1).Koch’s Quadric Island of n’th degree is obtained by changingeach horizontal segment of the (n-1)’th degree curve into the followingbroken-line (pict. 184.2).And by changing each vertical segment into the following broken-line(pict. 184.3).Picture 184.1


8Task: Draw Koch’s QuadricIsland of the third degreeon the paper. Write an algorithmto draw Koch’s QuadricIsland of the n’th degree.Input is the degree of thecurve: an integer number n,1≤ n ≤ 8.Picture 184.2Picture 184.3If you do not have enough experience working with graphicsCopy the file EGVGA.BGI to your working folder. Your programmight look this way:program Koch;uses graph; { module graph will be used }procedure draw (n: integer);begin... { the code of the procedure }end; { draw }In order to draw the curve the followingfunctions and procedures of graph module mightbe useful.function GetMaxX: integer;{ returns the maximum available x coordinate }function GetMaxY: integer;{ returns the maximum available y coordinate }var n, { the degree of the curve }driver, { graphic driver }mode: integer; { graphic mode }beginreadln (n); { inputs the degree of the curve }{ automatic graphic driver detection }driver := detect;{ graphic mode initialization }InitGraph (driver, mode,'');draw (n); { call to curve drawing procedure }readln;CloseGraph; { back to the text mode }end.procedure line(x1, y1,x2, y2: integer);{ draws line from (x 1, y 1) to (x 2, y 2) }STAGE IIIJUNIOR DIVISION185. House Painting. The modern many-storeyed house is being built. It willhave n floors. The floors are counted starting from the first floor. Each floor will bepainted with one of the two colors: white or gray. Two consecutive floors can bewhite, but can’t be grayTask. Write a program to find the number many ways the n floor house can bepainted.ExampleInput data is number of floors of the house n (1 ≤ n ≤ 21)Input Outputgiven from the keyboard.Output (one integer number) should be printed to the screen. 3 5


9186. Amusement Park. Two carousels(roundabouts) A and B are spinningcontrariwise (see picture 186.1).They have a and b trucks respectively.It is not possible to move from onetruck to another in the same carousel.But carousels are set so close to eachother that one can easily jump from onecarousel into another in the placewhere they adjoin.Picture 185.1At each moment of time one and only one truck of carousel A adjoins with one andonly one truck carousel B. Carousels spin at such speeds that after one moment of timetrucks, neighboring to the trucks that were adjoined at the previous moment, adjoin.At the picture below two black trucks adjoin. After one moment of time two graytrucks will adjoin. For example, someone entered carousel A. He can jump to a truckof carousel B and after carousel B turns around, He can come back to some truck ofthe carousel A.Task. 1) Given the numbers of trucks in both carousels a and b (20 ≤ a, b ≤ maxlongint).At the initial moment the naughty teenager is in the truck of carousel A. The task isto find the number of different trucks of carousel A that the teenager can visit withthe help of carousel B.2) It is known the number of trucks a of the carousel A. The task is to find theminimal number of trucks of carousel B such that the teenager from any truck ofcarousel A could get into any other truck of carousel A with the help of carousel B.Write a single program that could find both numbers (i.e. would solve the firstand the second parts of task).Input. The first line of the input file containsthe number of trucks a of carousel A andthe number of trucks b of carousel B.Number a is the input data to the both partsof the task, and number b is the input data tothe first part only.Picture 186.1InputExampleOutput24 22 1223


10Output. The first line of the output file should contain the solution to the first partand the second line – the solution to the second part.In half of tests the values of a and b will not exceed maxint.STAGE IIISENIOR DIVISION187. Jewels. Maze has a shape of orientedtree. An each dead-end of the maze there is ahidden jewel of particular value.There is one entrance to the maze only. Itis possible to move away from the entrance(i. e. in the indicated directions): one or morepaths go from each crossing. Only one wayleads to each crossing and each dead-end.See the picture: the crossings are markedwith circles and dead-ends are marked with littlesquares containing values of hidden jewels; theentrance to the maze is marked with asterisk.The boy comes into the maze and wantsto take one jewel as valuable as possible. Themaster of the maze accompanies the boy andhe wants the boy to take the jewel having assmall value as possible. The boy and the mastermeet at the entrance of the maze. At eachcrossing they have to choose which way togo (if only there is more than one path). Theboy chooses at the entrance, at the other crossing (where they found themselves afterthe boy’s choice) the master chooses, then the boy chooses and so on. Both the boyand the master know the maze very well (they know the values of each of the jewels)so they can choose the best way to go to.Write an algorithm to find the value of jewel the boy will take if the boy and themaster make optimal choices.Input. The first line of the input file contains the number of crossings N and thenumber of dead-ends M. At least one crossing (entrance) and at least one dead-endare given. The sum of numbers M and N does not exceed 10000. Crossings haveunique integers from the interval [1;10000].Following N+M lines of the input file describe either crossing or dead-end. Theyare presented in the arbitrary order.The line that describes crossing c begins with the letter „K“. If the crossing isentrance to maze, zero (0) comes after „K“; if there is a path from crossing d leading55*8 7 4 5 8 3 2 4Picture 187.147 10 51 2 9 38 7 4 5 8 3 2 4Picture 187.2


to crossing c, then number of crossing c is written. The last number in the line is thenumber of crossing c.Each line that describes dead-end begins with letter “A”. Two integers followthen: number of crossing from which there is a path leading to the dead-end and thevalue of jewel v (v – integer, 1 ≤ v ≤ maxint) that is hidden in the dead-end..Each letter and number are separated by a single space.Example:1. If crossing number 3 is being described inthe input data and you can go to it from thecrossing 5, the following line will describethe crossing 3:K 5 32. If the entrance to the maze has a number 4,the following line will describe the entrance:K 0 43. If there is a path to some dead-end from thecrossing 2, and the value of the jewel hiddenin the dead-end is 4, the line will be:A 2 4Output. The value of the jewel (single integer)should be printed to the screen.Input8 9K 10 9K 4 7A 9 5K 5 3A 3 3A 1 8K 0 4A 2 4K 4 5K 4 10A 1 7A 3 2K 7 1A 3 4A 9 8K 10 2A 7 5ExampleOutput5188. Presidential Election. Well-known politician K. Klevas decided to run forpresident. His team counts his popularity rating every day. Unfortunately the situationchanges, and rating goes up or down every day.The team of K. Klevas is willing to announce to the press such a summary ofpopularity rating changes that would not compromise the candidate. It is too dangerousto falsify data but it is possible to select several days and to make public only theratings of those selected days. While making the list of days (and ratings duringthese days) for the media, the days must be sorted in chronological order, but it is notnecessary to mention all days. It is allowed to eliminate any of days.Task. It is known that the rating was counted for d days in total. Write an algorithmto find such a longest list of days in chronological order, that popularity ratingswould only grow or at least would remain the same.If several solutions are possible, it is enough to find any one of them.Input. The first row of the input file contains the number of days d (3 ≤ d ≤ 15000).In the following d lines there are written ratings of corresponding days: rating ofthe first day is written to the first line, rating of the second day is written to thesecond one, etc. Rating is integer from the interval [-100; 100].11


12Output. The first row of the output file should contain k, the length of the longestlist of days. In the remaining k lines there must be written the numbers of days (inascending order) the list contains.ExampleInput Output Comments651051281341356List of days and ratings during these days are presented below:1 day 3 day 5 day 6 day5 5 8 13STAGE III, PART IIJUNIOR DIVISION189. Magic Square. Magic Square is a square table of natural numbers when thesums of each column, row and of both diagonals are equal.The n×n square table of natural numbers is given. Supposedly it is or could be amagic square, if we change one number only.Task. Write program to find if the given square is magic and if not, find out if it ispossible to get a Magic Square from it by changing one number only.Input. The first line of the input file contains a natural number n (2 ≤ n ≤ 50).Each of the following n lines contains n natural numbers (square table).The input data are given correctly: the sum of any row, line or diagonal will notexceed maxlongint.Output must be written in the file.If the given table is Magic Square, output must be MAGIC SQUARE.If it is possible to obtain the Magic Square by changing one number, the first lineof the output file should contain: POSSIBLE. The second line should contain thecoordinates of the replaced number(the number of line followed by thenumber of column) and the numberwe change to.If it is not possible to obtain theMagic Square output should be: NOTPOSSIBLE.Input312 17 1612 15 1114 13 18ExampleResultPOSSIBLE2 1 19190. Conspirators. The personae – conspirators – of one Jules Verne story wishingnobody could read messages they were sending to each other used the following method.


The message was hidden in the squaretable with contained different symbols(mostly letters). Square grid of the samesize with little holes in certain places wasused for decryption. For example, see picture190.1.The grid was put on the table and certainletters could be seen through the holes.The beginning of the encrypted messagewas obtained by reading those unhiddenletters from left to right and from the upperpart downwards. Then the grid wasturned by 180 degrees and the other letterscould be seen. After reading those lettersin the mentioned order, the end ofmessage was obtained. The whole messagewas decrypted like picture 190.2.The hidden message is there: GINKLAI YRA!After the message had been written to certain cells (according to the chosen grid),freely chosen letters and symbols were written into empty cells of the table and theencryption process was over.Task. Write a program to find the grid that should be used for encryption usinggiven the square table with symbols and the message. The input data are such that thesolution always exists. If several solutions are possible find any one of them.Input. The first line of the input file contains the message (not encrypted). Thelength of the message is from 2 to 100 symbols and it is necessarily divisible by 2.The second line contains the size N (1 ≤ N ≤ 50) of the grid (and of the letter table)used for encoding. The remaining N lines contain the letter table. Each line containsN symbols; there are no spaces between them.Only capital letters, punctuationmarks and space characters can be usedin the table and in the message. Neithermessage, nor any line of the table endswith space character.Output. The found grid should bewritten to the output file containing Nlines and each line containing N symbols.Holes should be marked with capitalO, and the remaining cells should bemarked with the capital X.G U D A S A SE M I E !N Y I A G O NA A A R B D KR N A A A K IŠ L V A ! M V! U S S O !GLPicture 190.1I N YAInputGINKLAI YRA!7GUDASASE MIE !NYIAGONAAARBDKRNAAAKIŠLVA!MV!USSO !K R APicture 190.2ExampleIResultOXXXXXXXXXXXXXXXOXXXOXXXXXXXXXXXXOXXOXOXXXXXXXXXX13!


14191. B. Bit Designs a Word Processor. Programmer B. Bit decided to design itsown word processor. One of operations that the word processor should be able toperform is finding the phrase in the given text.B. Bit decided that it would be convenient for him if the word processor couldcalculate how many times the indicated phrase appears in the given text and whilesearching for the phrase would apply these rules for matching upper-case and lowercaseletters:?if the phrase contains lower-case letters only, upper and lower-case letters shouldbe considered as equivalents. For example, the phrase jonas corresponds tojonas, JONAS, Jonas, jonaS, and etc.?if there is at least one upper-case letter in the phrase, upper and lower-case lettersshould be considered as different. For example, the phrase Jonas corresponds toJonas only but not to JONAS, jonas, jonaS, and etc.Phrases can cover each other. For example, in the text AAA phrase AA appears twice.If the last symbol of text line is dash (-) it means that word is moved to the otherline. When word processor is searching for a phrase, it ignores this dash and joinsparts of word in the different lines. If the last symbol is not a dash, it is considered thatone space character is after the last symbol in the text line.Note. The same dash in the middle of the line means punctuation mark thus thewords should not be joined.Task. Write an algorithm to calculate how many times the given phrase appears inthe text under the rules above.Input. The first line of the input file contains the phrase to be searched. The lengthof the phrase does not exceed 20; it contains upper and lower-case letters.The second line of the input file contains number k (1 ≤ k ≤ 30) of text lines whilethe remaining k lines contain the text.Length of the line (number of symbols)does not exceed 80. Text contains upperand lower-case letters, spaces, punctuationmarks, and numbers.Output (one integer) must be printedto screen.Inputlittle2A littlErabbit.ExampleResult1192. Winter in The Kingdom of Fancy. One day there was a heavy snow in theKingdom of Fancy and all roads became impracticable. It was not possible to clean allthe roads quickly, so the Government decided to clean only some selected roads, suchthat there would be a connection (not necessary direct) between any two towns. Tomake this work easier and cheaper, it was decided to choose the roads to be cleaned sothat the total length of the roads would be the least.


Below is sample of map of the Kingdom of42Fancy. Towns are marked with ringed numbers.Number written at the appropriate segment indicatesthe length of the road. The cleaned roads1087 20are marked with thicker lines. The total length35of the cleaned roads is the least.71Traffic is two-way in all roads and each roadconnects two different towns. Traffic net in thePicture 178.1Kingdom of Fancy is such that it is possible todrive from any town to any other one (of course, when roads are not snowbound) –directly or through intermediate towns.Task. Write an algorithm to find such a set of roads that after cleaning them it would bepossible to drive from any one town to any another town. The total length of the roads tobe cleaned should be the least. If several solutions are possible, find any one of them.Input. The first line of the input file contains the number of towns n (2 ≤ n ≤ 170).Towns are numbered from 1 to n.Further there are n lines and each of them contains n positive integers separatedwith space characters: in the i’th line there are written lengths of roads from town i toall other towns, herein j number in line i means the number of road that connectstowns i and j. If there is no direct road between towns i and j, then the length of theroad is marked with zero.None of the input data exceeds maxint. General length of all roads does not exceedmaxlongint.Note that number j in the line i always coincides with number i in line j because allthe roads are two–way. Besides, number i is always equal to 0 in line i, because thereare no roads – loops.Output. The first line of the output file should contain the total length of the roadsto be cleaned.In the remaining lines indicate the roads that will be cleaned – one road per line.Road is indicated by the numbers of towns it connects.The order of presenting roads is not important. It is possible to write numbersdescribing town in any order when indicating particular road.Example (coincides with the map presented in this task)Input Output Comments50 20 0 0 020 0 7 15 00 7 0 8 70 15 8 0 100 0 7 10 0422 13 25 34 315In this case the problem has the onlysolution; it can be presented notnecessarily as in this example. The firstline must remain the same, and the otherlines can be swapped. Numbers in thoselines can also be swapped.15


16193. Interpreter of Machine–language Codes. Nowadays programmers practicallydo not have to deal with machine–language codes. Essentially any program (for example,TURBO.EXE) is just a set of codes (binary digits) for a computer. Some numbers fromthis set mean processor instructions, the other ones – data for these instructions.We will analyze the following computing machine model. Machine has N fieldmemory. Fields are numbered from 0 to N–1. To any field an integer from 0 to 2 k – 1can be written. The machine has got one additional field of memory; we will call itregister R. One integer from the interval 0..N–1 can be memorized in this register.Any program executed by this machine is written to memory starting with a certainfield (the number of this field is called an address). The address of this field iswritten to register R.The firstfield ofan instructionThe secondfield of aninstructionThe thirdfield ofan instructionExplanations of instructions0 I J Number J is written to the field having address I.1 I J Number L[J] is written to the field having address I. Thecontent of the field J remains the same.2 I J Operation L[I] + J is executed. Result of composition iswritten to the field I (i.e. to the field having address I).3 I J Operation L[I] + L[J] is executed. Result of compositionis written to the field I.4 I J Operation L[I] –J is executed. The result of subtraction iswritten to the field I.5 I J Operation L[I] – L[J] is executed . Result of subtractionis written to the field I.6 I – Number is read from the keyboard, the cursor moves to anew line and the number that was read is written to thefield I.7 I – Number L[I] is printed to screen and the cursor moves toa new line.8 I J If L[I] > L[J], number 1 is written to the field I,otherwise zero is written to field I.9 I J If L[I] = L[J], number 1 is written to the field I,otherwise there is written 0.10 I J If L[I] < L[J], number 1 is written to the field I,otherwise there is written 0.11 I J If L[J] = 0, then it is moved to the field I, and theinstruction that is in that field is executed; otherwisefurther instructions are executed.12 I J If L[J] ≠ 0, then it is moved to the field I, and theinstruction that is in that field is executed; otherwisefurther instructions are executed.13 I – It is moved to the field I, and the instruction in that fieldis executed.14 – – Halt; Program is finished (the processor stops after thiscommand).


One instruction can involve 1, 2 or 3 fields of memory. All possible instructionscan be found in the table below. I and J are integers. If I or J means a memory address,then I or J belongs to interval 0..N–1, otherwise – to interval 0..2 k – 1. Dash in the cellmeans that the instruction involves less than three fields. The number recorded in thefield with an address X, we will mark L[X].Instructions are executed subsequently, one after another. If after executing 11, 12or 13 instruction it is moved to another field of memory, the instruction in the newfield is executed and then instructions which follow the last instruction in the newfield are executed (i.e. it is not returned to the previous position in memory).Task. Write an algorithm to execute program for the described machine. Assumethat during the execution of the program neither intermediate nor final data will notexceed the given limits and the program will not be cyclic.Input data are written in two input files. In the first line of the file INT.DAT thereare written two integers N (1≤ N ≤ 8000) and k (0 < k < 60).In the first line of the file PROG.EXC there are written the value of register R(program code starting address) and an integer M (1 ≤ M ≤ N). In the remaining Mlines there are written M numbers: valuesof memory fields from 0 to M –1.Number M indicates how manyfirst fields of memory occupy the programand the data (known in advance)for this program. In the remainingfields of memory there should be writtenzeros and those fields might beused during program execution.Note that during execution of thegiven program for described machine,you may need to enter from keyboardand print to screen.Explanation of the exampleThe memory will look like this:ExampleInputTextINT.DAT PROG.EXC printed to screen10 4 0 102761370012146Address 0 1 2 3 4 5 6 7 8 9Content 2 7 6 13 7 0 0 1 2 14Program is written starting with field 0 (i.e. field having address 0). The firstinstruction will change the content of the 7th field. There will be written 7. Then 13’thinstruction will be executed and it will be moved to the instruction in the 7’th field.There is a printing instruction in this field and after executing it, number 6 will beprinted to the screen. After that instruction in the 9th field is executed. It is a haltinstruction: program execution is over.Note. In a quarter of tests value of k will not exceed 15.17


18194. Hiker. Andrius decided to travel round Lithuania on foot and to visit surroundingsof the town he lives. The number of neighboring towns together with thetown where Andrius lives is equal to k. So, Andrius is willing to visit not less than 2and not more than k towns. In the map towns are indicated by points in Cartesiancoordinates. Andrius knows the coordinates (x i, y i) of all the towns.After visiting the last town, Andrius will return to his home town (i.e. the town thetrip was started from). Between any two towns Andrius will travel on foot by straightline joining these towns.Besides, Andrius is willing not to visit any town more than one time. The onlyexception is his home–town: Andrius will visit it twice: when starting his tour andfinishing it. Note that while walking on foot from one town to another Andrius canvisit the third town too, if only coordinates of this town belong to the segment joiningtwo first two towns.Sveiki! { Hello }Kiek daugiausia skirtingų miestų gali įeiti į maršrutą? { What is themaximum number of different towns that this route can include? }> 5Įveskite šių miestų koordinates (x, y):{ Enter the coordinates of those towns }1 miestas> 1 22 miestas> 3 13 miestas> 4 24 miestas> 5 45 miestas> 3 6Ačiū. { Thank you }Įveskite jūsų pasirinktus maršrutus. { Enter the routes you are considering }Įveskite miestų numerius ta tvarka, kuria norite juos aplankyti.Maršruto pabaigą žymėkite 0.{ Enter the numbers of the towns you are going to visit in the order of their visit. The end of the routeindicate by zero }> 1 2 3 4 5 0Ačiū. Kelio ilgis – 13,19 km. Maršrutas geras.{Thank you. The length of the route 13.19 km. The route is acceptable }Dar bandysite? (t/n){ Will you try again? (y/n)}> tĮveskite miestų numerius ta tvarka, kuria norite juos aplankyti.Maršruto pabaigą žymėkite 0.{ Enter the numbers of the towns you are going to visit in the order of their visit. The end of the routeindicate by zero }> 1 2 3 4 3 0Ačiū. Kelio ilgis – 11,12 km.Maršrutas netinkamas.{Thank you. The length of the route 11.12 km. The route is unacceptable }Dar bandysite? (t/n){ Will you try again? (y/n)}> nSiūlytume tokius maršrutus:{ The following routes are suggested: }trumpiausią - 1 2 3 4 5 (ilgis 13,19 km);{ the shortest one 1 2 3 4 5 (the length is 13.19 km);ilgiausią – 1 2 3 4 5 (ilgis 13.19 km).{ the longest one 1 2 3 4 5 (the length is 13.19 km).Geros kelionės!Have a good hiking!


Andrius has not quite decided how much time he would like to spend in his hiking tour.Task. Write a program to help the hiker to calculate lengths of the chosen routesand to find out if the selected routes satisfy his wish not to cross towns more than onceexcept for his home-town. The program should also found the shortest and the longestroute from the routes suggested by Andrius and satisfying his wishes.If there are several shortest or longest routes, it is enough to find out any one ofthem. It can be happen that none of the routes will satisfy the conditions.Input. Input data should be entered from the keyboard. It is known that number oftowns k belongs to the interval 2 ≤ k ≤ 15, and the coordinates of the towns x i, y ibelong to the interval 10000 ≤ x i, y i≤ 10000, i = 0, 1, …k. All data are integers.This is an interactive task. The dialog between the program and the user shouldlook as presented below. Output data (from keyboard) are printed in bold. All thedialog messages that can be printed out by your program should be found in the filePRAN.TXT. The message to be printed if none of the suggested routes are acceptableshould be found in the mentioned file.Assume that the entered data are correct. The same town can be indicated severaltimes, but not subsequently (i.e. it will not be possible to travel from some town A tothe same town A).The length of the route to be printed should be rounded in the precision of twodigits after a decimal.STAGE III, PART II19SENIOR DIVISION195. Packing Pascal programs. (Runtime limit – to 10 sec.; processor Pentium133 MHz) There are written some packing (data compression) programs. But sometimesone can achieve better results if it is known in advance how the file to be packedwill look like.There is given a file (extension. PAS) containing Turbo Pascal program (or library).None of the lines of this file end with a space character.Task. You should write two programs: 1) for packing the given file; 2) for unpackingthe given file. When packing and unpacking assume that capital and small Latinletters are equivalent. The given and unpacked programs should coincide.It is not allowed to use any of standard packing programs (arj, pkzip, rar and soon). During unpacking it is not allowed to use input file (PROGR.PAS) containing notcompressed program.First program: packing.Input. Program to be packed is written to the file PROGR.PAS. The size of the filewill not exceed 65000 bytes.Output. Write the packed program to the file PROGR.PAK.Second program: unpacking.


20Input. Program to be unpacked is written to the file PROGR.PAK. This is the filecreated by your packing program.Output. The unpacked program Should be written to the file PROGR.KAP.196. Parallel computations. One of possibilities to make the computations fasteris to execute some of them in parallel; this means that some operations are executed atthe same time. Some of modern microprocessors can execute independent commandsin parallel. The task is to write programs suitable for parallel computations.We will choose a simple model in this problem. Assume that a microprocessor canuse N cells of memory numbered from 1 to N, and it can perform in parallel infinitenumber of commands.Processor can perform these operations:L I J Content of the cell J is saved to the cell having address I.M I JA I JContent of the cell J is saved to the cell having address I. The contentof the cell J remains the same.Content of the cell I is added to content of the cell J, the result issaved to the cell I.S I J Content of the cell I is added to content of the cell J , the result issaved to the cell I.While performing commands in parallel holds the following restriction: At the samemoment it is not allowed to perform two or more commands using the same field. Forexample, it is not allowed to perform in parallel commands M 1 5 and M 2 5. Besides,it is not allowed to change sequence of operations executed with the same cell ofmemory. All commands must be executed. It is not allowed to optimize their.Adjustment of sequence of commands for computing in parallel is done in followingway: commands are grouped into blocks so that operations of commands in thesame block would not intersect (as it is required above). Hence all commands fromthe same block can be performed in parallel.After performing the initial sequence of operations and the same sequence adjusted toparallel computation, the content of memory cells must coincide with each other. If thesame command can be placed to several different blocs, it must be placed in the block withthe least number (assume that blocks are numbered in the order of execution).Task. Write a program to adjust the given sequence of operations for parallel computations,i.e. to group the given commands into blocks.Number of blocks must be the smallest one.Input. The first line of the input file contains the number of memory cells N(1 ≤ N ≤ 1000) and the number of commands K (1 ≤ K ≤ 10000). Commands arenumbered from 1 to K. Remaining K lines contain commands (one command per line).Each command contains one letter (L, M, A or S) and two numbers. If number means thenumber of a memory cell then it is from the interval 1..N, otherwise it can be any integer.


Output. Output must be written to the output file. Firstly output the list of commandsof the first block, then – of the second one and etc.The numbers of command of the same block should be written in separate lines,i.e. one number per line. Zero (0) as an indicator of the end of each block must bewritten in a separate line. Numbers of commands that belong to the same block mustbe presented in ascending order.ExampleInput Output Comments12 6L 10 4L 11 3M 12 11L 11 5S 10 12L 6 5126030450Three operations are performed in the first step:L 10 4L 11 3L 6 5One operations is performed in the second step:M 12 11Two operations are performed in the third step:L 11 5S 10 12197. Puzzle. (Runtime limit – to 3 min.; processor Pentium 133 MHz) n×m table (nrows, m columns) is filled with positive numbers. Two fields of the table are called neighboringif they have a common border. The numbers of three fields make equality, if• the first two fields are neighboring;• the second and the third fields are neighboring;• after placing one of the below listed arithmetic operations between thefirst and the second field it is possible to put an equality sign between theremaining two fields.The possible operations are composition,subtraction multiplication, and integer division(div). For example there is given a table(n = m = 3). Some equalities are shown in thepicture. One can make other equalities, forexample 19–7=12;Note. Assume, that if arithmetic operation12 7 44 19 2112 21 1Picture 197.112 7 44 19 2112 21 1= is placed between numbers a and b, then we can analyze expressions a = b and b = a.Task. Write a program to calculate the maximum number of equalities that can be madein the given table. A number written to each field can come into one equality only, and it canbe used only once in this equality. The result should be the number of possible equalities.Input. Positive integers n and m (3 ≤ n, m ≤ 100) are given on the first line of theinput file. Remaining n lines contain a table, each line containing m positive numbers(not exceeding maxint), separated by space.Output The maximum number of equalities (one integer) must be written to theoutput file.21+=×=


22ExampleInput Output Comments3 35 4 720 13 42 15 92 The number in the middle (13) can be used formaking several different equalities: 2=15–13,13=15–2, also 13–4=9 and 13=4+9. Accordingto task it can be used only once.5 4 720 13 42 15 9×=5 4 720 13 4-=2 15 9Picture 197.2×=5 4 7-20 13 4=2 15 9198. Around The World in 80 Days. (Run time limit – to 20 sec.; processorPentium 133 MHz) J. Verne had written in his book how Phileas Fogg traveled aroundthe world in 80 days. It might be he could have managed to complete his journeyfaster if he had a very good route.There are known schedules of various kinds of transport (trains, ferries and etc.) andthey are the same every day. The following information is given about each route: town ofdeparture, departure time, towns where it is stopped, time of journey between each twosubsequent stations. All schedules are presented in Greenwich Mean Time (GMT).The travelers will go to the East only, so all the schedules used in this task will beof eastward routes only.Change (for example, changing from one train to another) takes at least five minutes,so if, for example, one arrives at 13:03, it is possible to leave at 13:08 at theearliest. It is assumed that any transport arrives to and departs from any intermediatestation at the same minute.Task. It is known the town where P. Fogg lives. The beginning of the trip is exactlymidnight (at the GMT). Write a program which, given the schedules of various kindsof transport, would find out if it is possible to travel all over the world at all, and if itis possible, would report the earliest possible time of returning home (i.e. to the townthe journey was started).Input. The first line of the input file contains the number of towns M (2 ≤ M ≤ 500),the initial town P (1 ≤ P ≤ M), the number of routes R (1 ≤ R ≤ 200). It is assumedthat towns are numbered from 1 to M; trips are numbered from 1 to R.In the remaining lines there are written schedules of the routes. Several lines describeone route. In the first rout describing line there is written the number of thedeparture town nr (1 ≤ nr ≤ M), the departure time: hours h (0 ≤ h ≤ 23) and minutesmin (0 ≤ min ≤ 59), the total number of intermediate stations (including the arrival


station) ts (1 ≤ ts ≤ 150). In each of the further ts lines there is given informationabout one intermediate (or arrival) station: number of town a (1 ≤ a ≤ M), to which itis arrived and the duration of the journey to it from the preceding station in hours h(0 ≤ h ≤ 10000) and minutes min (0 ≤ min ≤ 59).Hence, the description of one route takes ts +1 line.Output the results to the first line of the output file. Write IMPOSSIBLE if it isimpossible to travel across the world, taking the given routes only; otherwise outputthe minimal time needed for the journey across the world: number of days(1day=24hours), hours and minutes.ExampleInput Output Comments5 3 33 5 35 31 2 444 21 75 7 181 8 23 13 16 235 6 23 23 18 122 17 322 0 46 The journey will take 2 days and 46 minutes.The traveler departs from the third town at5:35 and arrives to the first town after 2 hoursand 44 minutes, i.e. at 8:19. The travelerdoesn’t have any transport immediately, so heshould wait until morning and leave to thethird town at 8:23. The journey there takes 16hours and 23 minutes.23199. B. Byte Designs a Word Processor. Programmer B. Byte took example fromhis younger assistant B. Bit and decided to design a more powerful word processorhimself. One of the operations that the word processor should perform is to find aphrase in the given text.B. Byte decided that it would be easier for him if after indicating the fragment, hisword processor could find the places where the phrase was discovered in the text andwould make an appropriate table.Phrases can cover each other. For example, the phrase AMA repeats twice in thetext AMAMA. Upper-case and lower-case must be regarded while searching for phrase.Task. Write an algorithm to find all the places where the phrase is discovered in the text.Input. The first line of the input file contains two integers. These are the number oflines n (1 ≤ n ≤ 250) in the phrase and the number of lines m (1 ≤ m ≤ 25000) in the text.The further n lines contain the phrase and in the remaining m lines text is presented.Text and phrase can contain letters, spaces, numbers, and punctuation marks only.Phrase and text are reduced to lines, 80 symbols per line. The last line of phrase andtext can be shorter. None of the lines end with space.Assume that always the last symbol of any line belongs to the same word as thefirst symbol of the further line, i.e. the end of line never means the end of word.Output the results to the output file. If the given phrase was not encountered in thetext, write zero (0) to the output file. Otherwise in output file there should be such a


24number of lines, how many times theExamplephrase was found in the text. Each lineInputOutputshould contain two integers indicating the1 11 3place where the found phrase starts. Theselittleshould be the number of the line in theA little rabbit.text and the position in that line.Numbers of lines in the output file must be presented in ascending order.200. Checkers. On the black cells of square checkerboard there are placed several black and white pieces andone gray piece. White and black pieces do not make anymoves, and the gray one captures black pieces accordingto common rules: gray checker captures a black piece byjumping over it, diagonally, to the adjacent vacant squarebeyond it. The three squares must be lined up (diagonallyadjacent). But there is one restriction: the gray piececan capture black one only forward, i.e. number of lineof the gray piece can only increase.Task. Write a program to calculate the maximum numberof black pieces that can be captured by the gray piece in one move. One moveconsists of one or more jumps.Input. The first line of the input file contains the size of the board n (3 ≤ n ≤ 60).The second line contains the total number of pieces on the board M.Further there are such M lines. Each line indicates thecolor and the position of one piece in the following way:S x yS can be one of the three symbols: J means black, B– white, P – gray piece; x is the number of column, y –the number of row.Columns are numbered starting with one from rightto left and upwards. Cell (1, 1) is white. There is oneand only one line in the input data beginning with letterP (there is only one gray piece).Output. The maximum number of black pieces thatthe gray piece can capture with one move – should bewritten to the first line of the result file.Input98J 2 7J 3 6B 8 9J 5 6P 4 5J 5 2J 5 4J 7 8Picture 200.1ExampleOutput1201. Interpreter of Machine–language Codes. (Run time limit - 50 sec., processorPentium 133 MHz) Nowadays programmers practically do not have to dealwith machine–language codes. Essentially any program (for example, TURBO.EXE)is just a set of codes (binary digits) for a computer. Some numbers from this set meanprocessor instructions, the other ones – data for these instructions.


We will analyze the following computing machine model. Machine has N cellmemory. Cells are numbered from 0 to N–1. To any cell an integer from 0 to 2 k –1 canbe written. The machine has got one additional cell of memory; we will call it registerR. One integer from the interval 0..N–1 can be memorized in this register.Any program executed by this machine is written to memory starting with a certaincell (the number of this cell is called an address). The address of this certain cellis written to register R.The first The second The thirdfield of an field of an field of anExplanations of instructionsinstruction instruction instruction0 I J Content of the cell J is written to the cell having address I.1 I J Content of the cell L[J] is written to the cell havingaddress I. Content of the cell J remains the same.2 I J Operation L[I] + J is executed. Result of composition iswritten to the cell I (i.e. to the cell having address I).3 I J Operation L[I] + L[J] is executed. Result of compositionis written to the cell I.4 I J Operation L[I] –J is executed. The result of subtraction iswritten to the cell I.5 I J Operation L[I] – L[J] is executed . Result of subtractionis written to the cell I.6 I – Number is read from the keyboard, the cursor moves to anew line and the number that was read is written to thecell I.7 I – Number L[I] is printed to screen and the cursor moves toa new line.8 I J If L[I] > L[J], number 1 is written to the cell I, otherwisethere is written zero.9 I J If L[I] = L[J], number 1 is written to the cell I, otherwisethere is written 0.A I J If L[I] < L[J], number 1 is written to the cell I, otherwisethere is written 0.B I J If L[J] = 0, then it is moved to the cell I, and theinstruction that is in that cell is executed; otherwisefurther instructions are executed.C I J If L[J] ≠ 0, then it is moved to the cell I, and theinstruction that is in that cell is executed; otherwisefurther instructions are executed.D I – It is moved to the cell I, and the instruction in that cell isexecuted.E – – Halt; Program is finished (the processor stops after thiscommand).25


26One instruction can involve 1, 2 or 3 cells of memory. All possible instructionscan be found in the table below. I and J are integers. If I or J means a memory address,then I or J belongs to interval 0..N–1, otherwise – to interval 0..2 k –1. Dash in the cellmeans that the instruction involves less than three fields. The number recorded in thecell with an address X, we will mark L[X]Traditionally we use hexadecimal system (the digits of this system are 0, 1, 2, 3, 4,5, 6, 7, 8, 9, A, B, C, D, E, F). This system is used in all (also in input and outputinstructions) instructions.Instructions are executed subsequently, one after another. If after executing A, Bor C instruction it is moved to another cell of memory, the instruction in the new cellis executed and then instructions which follow the last instruction in the new cell areexecuted (i.e. it is not returned to the previous position in memory).Task. Write an algorithm to execute program for the described machine. Assumethat during the execution of the program neither intermediate nor final data will notexceed the given limits and the program will not be cyclic.Input data are written in two input files. In the first line of the file INT.DAT thereare written two integers N (1≤ N ≤ 100000) and k (0 < k < 257).In the first line of the file PROG.EXC there are written the value of register R(program code starting address) and an integer M (1 ≤ M ≤ N). In the remaining Mlines there are written M numbers: values of memory cells from 0 to M –1.Number M indicates how many first cells of memory occupy the program and thedata (known in advance) for this program. In the remaining cells of memory there shouldbe written zeros and those cells might be used during program execution.These numbers are written in the hexadecimal system.Note that during execution of the given program for described machine, you may need toenter from keyboard and print to screen.Explanation of ExampleMemory will look like picture 201.1.Program is written starting with cell0 (i.e. field having address 0). The firstinstruction will change the content ofthe 7th cell. There will be written 7.Then instruction D will be executed andit will be moved to the instruction inthe 7’th cell. There is a printing instructionin this cell and after executing it,number 6 will be printed to the screen.After that instruction in the 9th cell isexecuted. It is ahalt instruction:program executionis over.ExampleInputTextINT.DAT PROG.EXC printed to the screen10 4 0 10276D70012E6Address 0 1 2 3 4 5 6 7 8 9Content 2 7 6 D 7 0 0 1 2 EPicture 201.1


OLYMPIAD XII27STAGE IJUNIOR DIVISION202. Road Building. (Theoretical problem). In thepicture you can see the city plan. In the city there are threenew developments and a castle. There is a plan to open astud and the zoo. City council wants to build roads toconnect each development to all three attractions, i.e. theremust be built 9 roads overall. The council also wants theroads to cross each other the least number of times. Lengthand directness is nonessential.Task. Suggest city council the best project of roadbuilding.Picture 202.1203. Tomatoes. Itis known an interestingfact: if one places someRank of tomatoes originallyred tomatoes amongunripe tomatoes, theraw tomatoes will startRank of tomatoes after one daymellowing quicker.There are n tomatoesplaced in one row.They are numeratedRank of tomatoes after two daysfrom 1 to n (2≤n≤70).Picture 203.1One of these tomatoes is red. The number of the red tomato is m (1≤m≤n). Both neighborsof the red tomato will become red (mature) during the first day. During each nextday both neighbors of each red tomato will mature (if only they are immature). Payattention that the first and last tomatoes in the row have only one neighbor.Task. Write a program to calculate how many unripe tomatoes will remain in therow after d (1≤d≤30) days.Explanation. The data 9 4 2 correspond the presented pictures. The obtainedresult should be equal to 4.204. Will You Live in a Good Flat? Real estate agency offers you to buy a flat insome apartment house. The agency broker told you that there are n (1≤n≤100) flatsand m (1≤m≤5) stairwells in the house. Number of flats is the same in all stairwells.There are k flats in the landing of each floor in each stairwell. You are offered to buya flat having number nr (1≤nr≤n).


28Flats are numerated in the ordinary way: firstly flats of the first stairwell (floorsare counted starting from the first floor) are numerated, then flats of the second andetc. In the stairwells flats are numerated upwards.Task. Write a program to find:a) the number of floors in the house ;b) the number of flats in each stairwell;c) the floor of the flat offered to you;For example, if the input data are 24 3 2 6, the result should be: 4 8 3Explanation. Line of input data means that there are 24 flats, 3 stairwells in the house,there are 2 flats in the landing of each floor, and the number of flat you are offered is 6.From this data you can say that the house has 4 floors, there are 8 flats in eachstairwell, and flat you are offered to buy is on the 3rd floor.STAGE ISENIOR DIVISION205. Orienteering Competition (theoretical problem). In the picture there is given amap of locality containing points (marked with circles) and pathways connecting them.4 7WestVakarai1Picture 205.1Contestants must start runningfrom the start (the initialpoint), run each pathway onceand reach finish. The samepoint (even start and finishpoints) can be run through forseveral times. Start and finishpoints must be different.Unfortunately, whilepreparing the map layoutwith the computer, the arrows,which were indicatingthe directions of the pathways,were lost. Paste-updesigner could only rememberthat finish was to the West from the start. After studying the map closely it appearedthat it is possible to determine unambiguously the start and finish points.Task. Find start and finish points. Explain your solution briefly.Note. To make it easier to explain the solution, all points were numerated randomlyfrom the interval [1..9].206. Tomatoes. It is known an interesting fact: if one places some red tomatoesamong unripe tomatoes, the raw tomatoes will start mellowing quicker. There are n695283EastRytai


29Rank of tomatoes originallyRank of tomatoes after one dayRank of tomatoes after two daysPicture 206.1tomatoes placed in one row. They are numerated from 1 to n (4≤n≤200). Three ofthese tomatoes are red. The numbers of the red tomatoes are m 1, m 2, m 3(1≤m i≤n).Both neighbors of each red tomato will become red (mature) during one day. Naturally,the first and last tomatoes in the row have one neighbor only.Task. . Write an algorithm to calculate how many unripe tomatoes there will remainafter d (1≤d≤30) days.Note. In the input data the numbers of red tomatoes are presented in ascending order.Example. These data 19 2 13 15 2 correspond the pictures above. The obtainedresult should be equal to 8.207. Multiplication à la russe. À la russe is a multiplication algorithm to multiplytwo positive integers (let us mark them N M). It is described and illustrated below.Initially zero is assigned to the intermediate product.If the first multiplier is odd, then the second one is added to the intermediate product;otherwise the intermediate product remains unchanged. Then the first multiplier is dividedby two (integer part is taken), and the second one is doubled by adding it to itself.Operations are repeated. When the first multiplier becomes equal to one, operationsare performed for the last time, and the obtained intermediate product becomesequal to the product of numbers N and M.For example, let us multiply the numbers 325 and 6874.The first multiplier The second multiplier Intermediate product325 6874 6874162 13748 687481 27496 34370=6874+2749640 54992 3437020 109984 3437010 219968 343705 439936 474306=34370+4399362 879872 4743061 1759744 2234050=474306+1759744We obtain: 325×6874==2234050;Such a multiplication algorithm resembles the binary multiplication used in thehardware of a binary computer.


30Task. Write a program to multiply two numbers in this way. It is known that theproduct will not exceed maxlongint.All different intermediate values and the calculated product of the given numbersmust be written. Input data corresponding the example above would be 325 6874,and the result would contain four numbers:6874 34370 474306 2234050.STAGE IIJUNIOR DIVISION208. Who Had Stolen the Wallet (theoretical problem). The wallet had disappearedin one office. All five persons who were in that room were interrogated and thefollowing evidences were obtained:EMILIA: 1. I did not steal it;4. I have never stolen anything in my life;5. Tadas stole it;JUDITH: 1. I did not steal it;4. My father is rich enough and I have my own wallet;5. Rita knows who did it;DARIUS: 1. I do not know anything about stealing;4. I met Rita one year ago;TADAS:5. Tadas did it;1. I am innocent of this crime;4. Rita did it;5. Emilia is lying when she says I did it;RITA: 1. I did not steal the wallet ;4. Judith is guilty;5. Darius can vouch for me, because we are friends from childhood;Further interrogation let to determine that all five persons gave two true and onefalse evidence.Task. Determine from the given data of interrogation, who had stolen the wallet.Explain your solution.209. Interesting Sequence. Sequence is generated in the following way. The firstmember is any odd natural number greater than one. Each further member is equal to:p div 2, if p is even;3p+1, if p is odd;where p is the previous member of the sequence. The sequence is finished when one(1) is obtained. For example, the first member of the sequence is equal to 7. Then thefollowing sequence is obtained:7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1Supposedly, this sequence is always finite. However, this assumption has not beenproved yet.


Task. Given the first member of sequence p (3≤p


32Further interrogation let to determine that all five persons gave two true and onefalse evidence.Task. Determine from the given data of interrogation, who had stolen the wallet.Explain your solution.212. Draughts. We have rank of n (3≤n≤10) squares.Squares are numerated from 1 to n from left to right. There isa heap of draughts standing on each square (from 0 to 10draughts). It is allowed to swap to heaps of draughts if theyare in the neighboring squares.Task. Write a program to rearrange heaps of draughtsso that the heights of heaps (i.e. the number of draughts inthe heap) would be in non ascending order. The programshould output the number of moves and moves themselvesin the order of their performance. Move is indicated bythe numbers of squares of swapped heaps.For example, there are given 3 heaps. There are 2, 5and 4 draughts in them. It is possible to rearrange heapsof draughts within two moves. The possible output is:21 22 3Pictures 212.1 illustrate this example.1 2 3The given heaps1 2 3The second move is performed1 2 3The first move is performedPicture 212.1213. Ornament. The ornament consists of n××n black and white squares. Newornament is obtained by scrolling the given ornament in different directions. It ispossible to scroll to the left, to the right, upwards and downwards.When scrolling ornament to any side, all rows (columns) are scrolled over oneposition, and the outside row (column) is moved to the opposite side. Scrolling isillustrated in pictures presented below.Input. The first line of the input file contains the size of the ornament n (3≤n≤10).In the second line there is written a sequence of commands. The sequence of commandsconsists of letters K (to the left), D (to the right), V (upwards), A (down-The ornamentbefore scrollingThe ornamentscrolled upwardsThe ornamentscrolled downwardsPicture 213.1The ornamentscrolled to the leftThe ornamentscrolled to the right


wards). There are no spaces between letters. There are not more than 25 commands inthe sequence. The remaining n lines contain the ornament itself. Black squares areindicated by capital “O”, the white ones – by dots (.).Task. Write a program to draw the new ornament obtained from the given ornamentby performing the given commands.Example: (corresponds to picture a):Input Output Picture that corresponds to the result5KKKAAADOOOOO.O.....O..O..O.OO..OO.....O.O...OOOOOOOO....OSTAGE III, PART I33JUNIOR DIVISION214. Currencies. In many Western European countries conversion currency ratesbetween euro and national currencies are fixed. Then the ratio between different currenciesof these countries also becomes fixed.Given a table of currency rates of N countries (countries are numerated from 1 toN). The number in the i’th column and j’th row indicates how many currency units ofcountry j costs currency unit of country i . Table is not completed, i. e. there are not allconversion rates are known. Zeroes are written instead of unknown conversion rates.Task. With reference to the data in the table restore as many as possible unknownconversion rates, i.e. as many zeroes as possible must be changed with conversionrates. The result is the initial table of conversion ratios complemented with the newlycalculated rates (if it is impossible to calculate conversion rates between currencies ofsome countries, zeroes should remain).Input. The first line of the input file contains the number of countries N (2


34ExampleInputOutput5 50 2 4 0 0 1 2 4 4 00 1 0 0 0 0.5 1 2 2 00.25 0 1 0 0 0.25 0.5 1 1 00 0 1 1 0 0.25 0.5 1 1 00 0 0 0 1 0 0 0 0 1215. Fortune-teller. One fortune-teller can predict the future and foretell the probabilitythat one person (call him/her A 1) will meet another person (call him/her A 2).The probability is expressed in percents (natural number from 1 to 100).The fortunes are told in the following way: person A 1who applies to fortuneteller,tells his/her given and family names as well as the given and family names ofA 2. For example, Jonas Jonaitis and Janina Petrienė. Fortune-teller writes all data(given name and family name of A 1and A 2) into one row without space characters(it is assumed that capital letter and lower-case letters are the same), for example:JONASJONAITISJANINAPETRIENĖThis will make the first group of letters.The second group of letters will consist of several rows of letters.Fortune-teller shapes this group like this: takes letters of the first group in turn and• if the first row of the second group does not contain the letter, then she addsit to the end of the first row;• if the first row of the second group contains the letter, then she writes it underthe same letter in the column.Then under the second obtained group of letters fortune-teller writes how manytimes letters repeat in each column. Long line of digits is obtained – call it number sk1.For the first group of letters presented in example above the second group andnumber sk1 will be:JONASITPERĖJONASIT EJ NA INA IN32542421211 This is number sk1Further fortune-teller forms number sk2 in the following way: adds the first digitof sk1 to the last one and equates the obtained sum with the number sk2. Then sheadds the second digit of sk1 to last but one and writes the obtained sum to the end ofnumber sk2, then she adds the third digit from the beginning to the third digit from theend and writes the obtained sum to the end of sk2. Fortune-teller performs these


actions until there are no more digits of number sk1 left or until one middle digitremains, – in this case she just adds it to the end of sk2.Number sk3 is obtained from number sk2 in the same way and etc., until theobtained number becomes smaller or equal to one hundred. For example:32542421211437544 { 4=3+1, 3=2+1, 7=5+2, 5=4+1, 4=2+2, 4=4 }8712 { 8=4+4, 7=3+4 , 12=7+5 }108 { 10=8+2, 8=7+1 }90 { 9=1+8, 0=0 }Number 90 will be the result. It means that the probability that A 1will meet A 2is90 percent.Task. Write a program to calculate the probability for two persons to meet if theirgiven and family names are known.Input. The first row of input file contains the given name and the family name ofA 1, while the given and family names of A 2on the other line. A single space characterseparates given and family names. The length of a given and family name togetherdoes not exceed 25 symbols.Output. The probability of meeting A 1with A 2– one integer number – should beprinted to the screen.STAGE III, PART I35SENIOR DIVISION216. Game With a Maze. (Run time limit – to 20 sec.; processor Pentium 133MHz). The game consists of quadratic plate with a maze seamed in it. There is a ballinside the maze. The plate is covered with glass and so the ball cannot fall out of theplate. The plate is fixed to the vertical wall so that it is possible to rotate it by 90° tothe left (anticlockwise) or to the right (clockwise). During the rotation, the ball doesnot move (it is fixed). After the rotation is finished, the ball is released and it fallsdown until it strikes an obstruction (wall of the maze) ant its position is fixed again.Task. Given a maze of size n, the initial coordinates of the ball (x, y) and the sequenceof rotations, indicated with letters K or D. Squares of the maze are numerated from thebottom left corner beginning with 1 (x indicates rows, y – columns). Write a program todetermine where the ball would land up after performing the sequence of rotations.Input. The first line of the input file contains the size of the maze n (1 ≤ n ≤ 1000) andthe position of the ball – two numbers – x and y (1 ≤ x, y ≤ n). The second line containscommands – sequence of letters K and D. There are no spaces between these letters (thereis at least one command, the total number of commands does not exceed 5000).In the remaining n lines there is presented the maze itself: 0 indicates a passageand 1 indicates a wall.Output. Two numbers (coordinates of the ball) – must be written to the output file.


36ExampleInput Output Explanation10 3 7DDDKD11111100000011110110110000100110011000001101110110000000100010001100000000110000100100110010011011118 31111110000001111011011****100110011*****110111011*000000100*100011000*000011****10010011001001101111217. Assign Statements. (Runtime limit – to 10 sec.; processor Pentium 133 MHz).We will analyze assign statements having the following structure::=;The present notation means: – any integer variable (integer), having a name that consistsof one small letter from Latin alphabet; – addition (+), or multiplication (*) operation; – any non-negative integer.Examples of assign statements described above:x:=y+3;z:=z*5;a:=b+0;Task. There is given a natural number S and a sequence of assign statements of thedescribed structure (not less than two statements). Write a program to cross out somestatements of this sequence (except the last one – it can’t be crossed out) so, that afterperforming the sequence of remaining statements, the value of the variable in the laststatement would became equal to S. If it is possible to do this in several ways, chooseany one of them. The initial values of all variables are equal to 1.The order of statements can’t be changed, for example, if we have crossed out thesecond statement, and we have left the first and the third, then in a new sequence thefirst statement must be executed before the third one.If after performing the initial sequence (without crossing out anything) we obtainthat value of the last statement is equal to S, then that sequence can be the result.Input. Number S is written in the first line of the input file and the number ofassign statements N is written in the second line. The following lines contain assignstatements of the structure described above (one statement per line). Statements are


written from the first position of line. There are no spaces between the terms of statement.There is a semicolon (;) at the end of each statement (without any space).Output. The first line of the output file should contain NO, if it is impossible toreduce sequence so that after executing it the value of the last statement would beequal to S, or word YES, if it is possible to do this. In this case in the further lineswrite the numbers of remaining (i.e. not crossed out) statements, one statement perline (it is assumed that the statements are numerated in the order of their appearancein the input file starting from 1).ExampleInput Output Explanation124n:=n*2;m:=n+1;n:=n*3;k:=n+6;YESP134After executing the sequence (which must containthe last (fourth) statement, we must obtain 12. Ifwe cross out the second statement (in this case itdoes not even matter), then we will see that theresult is really 12. (After executing the firststatement, value of n becomes equal to 2, afterexecuting the third one – 6 and after the fourth –124n:=n*2;m:=n+1;n:=n*0;k:=n+6;94n:=n*2;n:=n+1;n:=n+2;k:=n+4;value of k becomes equal to 12).NO The value of k should become equal to 12.Therefore the final value of n should be 6. Thethird and the first statement change value ofvariable n. After executing the third statement thevalue of n becomes equal to 0, and after executingthe first one it becomes equal to 2. There are noother possibilities to change the value of n; In thiscase we the answer is NOYES1234In this case we must take all the statements of thethe initial sequence (otherwise the final value of kwould be less than 9).Restrictions1. Number of statements in the input file does not exceed 22.2. In test cases the statements will be such that overflow will never (e.g., aftercrossing out any part of the sequence and executing the remaining statements) occur.STAGE III, PART II37JUNIOR DIVISION218. Table (Runtime limit – to 10 sec.; processor Pentium 133 MHz). The tableof numbers consists of 4 rows and N columns (N ≤ 20). The table can contain only the


38numbers zero (0) and one (1). However all the numbers are missing. It is only knownthe sums of each column and each row.Task. Write a program to complete the table (if it is possible to do this). If severalsolutions are possible, find any of them.Input data are written to the input file. The first line contains the number of columnsN (N ≤ 20), while the second line contains the sums of numbers in each column(N numbers). In the third line there are written sums of each row numbers (four nonnegativenatural numbers).Output. The result must be written to the output file. The first line of the outputfile should contain YES, if the solution exists, or NO otherwise. If the solution exists,in the second line should contain the first row of the completed table, the third lineshould contain the second row of the completed table, etc.ExampleThe initial table (N=4)? ? ? ? 1? ? ? ? 3? ? ? ? 3? ? ? ? 44 3 3 1The result table1 0 0 01 1 1 01 1 1 01 1 1 1Examples of input and output dataInput Output Explanation44 3 3 11 3 3 4YES1 0 0 01 1 1 01 1 1 01 1 1 1Corresponds example in task219. Maze (Runtime limit – 2 sec.; processor Pentium 133 MHz). Maze consistsof rooms and passages between them. It is possible to move in indicated direction inports only. There are no cycles in the maze.There is either prize or penalty in each room – it is expressed in points. When theplayer comes into room with a prize, points are added to player’s account, and if thereis penalty in a room, then player’s account is reduced, .i.e. points of penalty are subtracted.Player can choose which room to start move through the maze from and where tostop; but he must visit at least one room of the maze.


Task. Write a program to find the largest number of points the player can score (ifthere are penalties in all rooms only, then the largest number of points will be negative).At the beginning the player’s account is empty, i.e. it contains zero points.Input. The first line of the input file contains the number of rooms N (2 ≤ N ≤ 80)in the maze. Further there are N lines, corresponding the rooms (rooms are numeratedfrom 1 to N). In each line the first number T is the number of points of the room: if T > 0,then it is a prize, if T< 0, then it is a penalty. Next there is written number P, which isequal to number of passages going out of particular room, then there is numbers of Prooms where those passages lead. Numbers are separated by space.Output. The only line of the output file should contain one number: the largestnumber of points that can be scored in the maze.Examples of input and output dataInput Output Explanation751 Traveler’s route: 3, 1, 5, 4.1 1 51 5 4-1 1 51 -10 5010 2 1 250 1 7-10 1 4-2 1 33 2 7-3 010-1 -3396-24-1 0-7 1 4-2 2 1 2-3 0-1 Traveler’s route: 1 .220. Cents. (Run time limit – to 1 sec.; processor Pentium 133 MHz). Let us beoptimistic and say that in 200x year the income of all the citizens will increase somuch that we will decide to refuse of coins of 1 and 2 cents. In that case the prices ofgoods will still be calculated in the accuracy of cent, but the whole sum of pay must berounded off in accuracy of 5 cents: 1 and 2 cents are replaced with 0 cent; 3, 4, 6 and7 cents are replaced with 5 cents; 8 and 9 cents are replaced with 0 cents.Imagine, that a thrift customer comes into a small shop selling different things andhe wants to buy goods and to profit from rounding off cents as much as possible. So hebuys goods in several purchases to benefit from it.


40Task. Write a program to calculate the maximum profit, and then to find the minimumnumber of purchases (walking past counter) to gain that profit. There can be asituation when it is not possible to benefit and even a certain sum of money is lost. Inthis case the answer (profit) will be negative.Input. The first line of the input file contains the number of items N the customerwants to buy. In the remaining N lines there are presented prices of goods expressedin cents. The customer can not buy less than N items.Output. The first line of the output file should contain two numbers: customer’sprofit, expressed in cents, and the number of purchases (walking past counter).Examples of input and output data:Input1 Example 32232 Example 11023Output2 1-2 1221. Asterisks. (Runtime limit – to 1 sec.; processor Pentium 133 MHz). There isgiven a very long row consisting of asterisk and space symbols set in the followingorder: one asterisk, one space character, two asterisks, two space characters, threeasterisks, three space characters, etc.Task. Write a program to determine which symbol is in k’th position.Input data – one integer number– is introduced from the keyboard. It is the positionk (1 ≤ k ≤ 30000) of the symbol to be found.The Ouput –– word SPACE or ASTERISK – should be printed to the screen.222. Acquaintances. N quests (numbered from 1 to N) were invited to attendsome event.It was known in advance which persons were familiar with each other before theevent. Two guests would certainly became acquaintedwith each other during the event, if theyhad or made common acquaintance during theevent.Organizers of the event, knowing which guestswere familiar with each other, were sure that allguests would became acquainted. However one persondid not attend the event, and due to this not allthe guests became acquainted.Task. Write a program to determine the guest whodid not attend the event.ExampleInput Output742 2 72 1 42 4 54 2 3 6 72 3 62 4 52 1 4


Input data are presented in the input file. The first line of the input file containsthe number of guests N (2 < N ≤ 200). The second line contains the numbers of gueststhe first person was familiar with: the first number in the line indicates how manyguests the first guest knew, further there are presented the numbers of the guests. Thethird line contains the numbers of guests the second guest was familiar with, etc.Output – the number of absent guest – must be written to the output file.Note. If several solutions (absent persons) exist, output any one of them.STAGE III, PART II41SENIOR DIVISION223. Game-machine. (Run time limit – to 3 sec.; processor Pentium 133 MHz).On the screen of the game-machine there are ten squares. One digit (from 0 to 9) canbe seen in each square. There are buttons under squares, numerated from 1 to 10.Each button controlscertain squares.Their connectionsare presented intable below.When a button ispressed, the numbersin squares controlledby this buttonare increased by one.If the number seen inthe square was 9, itwould become 0.Number of Numbers of squares controlled by buttonsbutton1 4, 5, 8, 9, 102 9, 103 8, 104 3, 5, 9, 105 6, 8, 96 2, 3, 4, 5, 8, 107 1, 2, 4, 6, 8, 9, 108 109 7, 8, 1010 5, 7, 9, 10Task. Write a program, which for the given sequence of numbers of squares findssuch the shortest sequence of pressing buttons (if only such exists) that after performingit digits in all squares become the same.Input. The only line of input file contains 10 digits, separated by a single spacecharacter.Output. The first line of the output file must contain IT IS IMPOSSIBLE, if it isnot possible to find the described sequence of pressings, or IT IS POSSIBLE, if it canbe found. In this case the number of pressings N must be written to the second line,and the numbers indicating how many times a certain button was pressed must bewritten to the remaining ten lines (one number per line). If the button was not pressed,zero must be written.Notes. 1. If several solutions (shortest sequences) exist, output any one of them.2. If all digits are the same in the input data, then the solution must be IT ISPOSSIBLE, and number of button pressings must be equal to zero.


42Examples of input and output data:Input Output Explanation4 4 4 4 4 4 4 4 4 3 IT IS POSSIBLE100000001000 0 0 0 0 0 0 9 9 7 IT IS POSSIBLE30110000100It is enough to press the 8thbutton only.After pressing 2nd, 3rd and8th buttons, we obtainzeroes in all squares.224. Board. A rectangular board consists of N×M (N rows, M columns) squares.Some squares were cut out (the board might have became not connected) It is desirableto cut the remaining board into solid rectangles, made of exactly two squares.Task. Write a program to calculate the maximum number of such rectangles, thatcan be cut out from this fenestrate board.Input. The first line of the input file contains two numbers: N and M (2 ≤ N, M ≤ 50).The second line contains the number of cut squares (if no squares were cut out, then thisnumber is zero). Further there are as many lines, as many squares were cut. Each linecontains the coordinates of a cut square (two numbers): the first coordinate (from 1 toN) indicates row, the second one (from 1 to M) indicates column.Output – the largest number of rectangles that can be cut from the given board –should be written to the result file.Examples of input and output data:


43Input Output Explanation3 4 342 42 32 21 3One of the possible variants of cutting4 4 451 13 32 24 41 4One of the possible variants of cutting225. Acquaintances. N guests were supposed to attend the event. Guests are namedwith numbers from 1 to N.It was known in advance which of these persons were familiar to each other. Twopersons would certain became acquainted with each other during the event, if they hador made common acquaintance during the event.Organizers of the event, knowing the situation were sure that all guests would becameacquainted. But one person did not attend the event and not all the guests becameacquainted.Task. Write a program to determine the guest who did not attend the event.Input. The first line of the input file contains contain the number of guests N(2 < N ≤ 200). The first number of the secondline is the number of persons the first personwas familiar with before event. Further there arepresented the numbers of the guests the firstguest knew. The third line contains the numberof persons the second person is familiar withand etc.Output – the number of absent guest – mustbe written to the result file.Note. If several solutions (absent persons)exist, output any one of them.Input72 2 72 1 42 4 54 2 3 6 72 3 62 4 52 1 4ExampleOutput4


44226. Expanding Polynomial Into Multiplicands. (Runtime limit – to 3 sec.;processor Pentium 133 MHz). From the course of mathematics you know how toexpand expressions into multiplicands; for example, the expression ab+ac+3b+3ccan be expanded as a product of two multiplicands:ab+ac+3b+3c = a(b+c)+3(b+c) = (a+3)(b+c)In general, decomposition into multiplicands is rather complicated problem, but inspecial cases (as it will be presented below in the task) it can be solved rather easily.The polynomial of class A will be called the polynomial with the following properties:• 2nd degree is a polynomial;• has two or more variables;• it is reduced (i.e. similar terms are collected);• all the monomials have integer positive coefficients;• the coefficients by squares are equal to one;The polynomial of class B will be called the polynomial with the following properties:• 1st degree is a polynomial;• has two or more variables;• it is reduced (i.e. similar terms are connected);• all the monomials have integer positive coefficients;Examples of the polynomials of class A:2ab+4ac+af+3ef+cea 2 +b 2 +bcxyExamples of the polynomials of class B:3a+f+2ga+78bxExamples of expressions that do not belong to the class A:ab+b The monomial b is not of the second degreeab-bc The coefficient before bc is not positiveab+abc The monomial abc is not of the second degreeab+1,5xy The coefficient before xy is not integer2a 2 +b 2 The coefficient before a 2 is not equal to oneExamples of expressions that do not belong to class of polynomials B:b+b The polynomial is not reducteda-c The coefficient before c is not positiveab+c The monomial ab is not of the first degreeTask. Write a program to expand the polynomial of class A into product of twopolynomials of class B.Input. There is one number N (N


small Latin letters, multiplicationsign is omitted (as it is commonin mathematics). The degree (inthis problem it can be equal totwo only) is written withoutspaces right after the variable,for example, a 2 is written as a2.Numerical coefficient (it can notbe larger than 10000) is writtenbefore variable and it is omitted,if it is equal to one (as is acceptedin mathematics).Output. Write zero (0) to thefirst line of the output file, if it isnot possible to expand the polynomialinto multiplicands andnumber K – if it is possible. HereK means the number of ways toExamples of input and output dataInput Output Explanation2abac1ab+cab+ac=a(b+c)2aba26xyzxtx25uy25uz25ut2a2b21aa+b1x+25uy+z+tab+a 2 =a(a+b)xy+zx+tx+25uy+25uz+25ut=(x+25u)(y+z+t)expand the polynomial into multiplicands. In the latter case the second and the thirdlines of the output should contain the first and the second multiplicands of any way ofexpanding.227. Numbers (Run time limit – to 20 sec.; processor Pentium 133 MHz). A setof N (1 ≤ N ≤ 10) integers and one more integer S are given. The task is to determinewhether it is possible to choose such a subset from the given set that the sum of all thenumbers from the subset would be equal to S.Task. Write a program to find such a subset of numbers that their sum would beequal to S. If several possible solutions exist, find any one of them. If it is not possibleto obtain the given sum it must be reported.The input data are entered from the keyboard. Firstly integer S (the given sum) isentered. Then in the separate line N (1 ≤ N≤ 10) integers are entered. Numbers willbe written into one line, separating them by at least one space character.Print the results to the screen in the form of equality. Example:1389 == 1202 + 79 + 100 + 8If it is not possible to obtain the given sum, write IMPOSSIBLE after the equality.Note.: Because the input data are introduced from the keyboard, and the resultsare written to the screen, it is desirable to create comprehensive interface.0a 2 +b 2 =????????45


46OLYMPIAD XIIISTAGE IJUNIOR DIVISION228. Hamming Code. (Theoretical problem). During transmission through telecommunicationnetwork, the messages (data) can be corrupted. To avoid this, messagesare coded.A 4-bit message must be transmitted: p=b 1b 2b 3b 4. Bit is zero (0) or one (1). Possibleerrors are replacing zeros with ones or vice versa. To identify bad bit three extrabites are attached:b 5=b 2+b 3+b 4;b 6=b 1+b 3+b 4;b 7=b 1+b 2+b 4;Values of bites are summed up withmodule two. A table for summation ofbites is presented (pict. 228.1).Picture 228.1The encoded message contains sevenbits: p coded=b 1b 2b 3b 4b 5b 6b 7. Such a code is called a code of Hamming.byte 1 byte 2 byte 1 +byte 20 0 00 1 11 0 11 1 0Consider the example: the message to be transmitted is 0110. We calculate:b 5=1+1+0=0; b 6=0+1+0=1; b 7=0+1+0=1. The encoded message will be:p coded=0110011.Task. Four encoded messages were received: 1100011, 1010110, 1111111 and0101010. It is known the reliability of telecommunication lines: during transmissiononly one bit can be altered. Determine, whether the messages were transmitted correctly.Explain your solution.229. Japanese Calendar. The old Japanese calendar contained cycle of 60 years.All years in the cycle were enumerated from 1 to 60 and they were grouped in pairs.Each pair had its own color (green, red, yellow, white and black). Colors of the yearsof each cycle were distributed like this:• 1, 2, 11, 12, 21, 22, …, 51, 52 Year – green color;• 3, 4, 13, 14, 23, 24, …, 53, 54 Year – red color;• 5, 6, 15, 16, 25, 26, …, 55, 56 Year – yellow color;• 7, 8, 17, 18, 27, 28, …, 57, 58 Year – white color;• 9, 10, 19, 20, 29, 30, …, 59, 60 Year – black color;It is known that new cycle of 60 years began in 1984 and will be over in 2043;1984 and 1985 were the years of green color, 1986 and 1987 were the years of redcolor, 2043 will be the year of black color.Task. Write a program to determine the color of the given year m (1800≤m≤2200).


230. Interest. A man went to borrow some money from a moneylender. The moneylenderagreed to lend and asked to repay money next month in the following way:on the first day of the month – 1 litas, on the second – two litas, on the third – fourlitas, i.e. every day to repay twice as much as the day before. On the day when the debtcould be paid off, the debtor would have to repay all rate of that day too. The overpaidsum would be the moneylender’s interest.Task. Write a program to calculates how many interest in litas would a moneylenderget for the borrowed n litas.Example. If a man had borrowed 5 litas, a trader would get interest of 2 litas.47STAGE ISENIOR DIVISION231. Hamming Codes. (Theoretical problem). During transmission through telecommunicationnetwork, the messages (data) can be corrupted. To avoid this, messagesare coded. We will only analyze messages containing bits and such telecommunicationlines, which during transmission of one message, alter not more than one byte.A 4-bit message must be transmitted: p=b 1b 2b 3b 4. Bit is zero (0) or one (1). Possibleerror is replacing zero with one or vice versa. To identify bad bit three extra bitesare attached:b 5==b 2+b 3+b 4;b 6==b 1+b 3+b 4;b 7==b 1+b 2+b 4;Note: values of bytes are summed up with module two, i.e. adding two high bytes,zero byte is obtained.The encoded message contains seven bits: p coded=b 1b 2b 3b 4b 5b 6b 7. Such a code iscalled a code of Hamming.Consider the example: the message to be transmitted is 0110. We calculate:b 5=1+1+0=0;b 6=0+1+0=1;b 7=0+1+0=1.The encoded messagewill be: p coded=0110011.In order to find outwhether an error was made,the following sums are calculated(with module two):S 1==b 4+b 5+b 6+b 7;S 2==b 2+b 3+b 6+b 7;S 1 S 2 S 3 Which byte is the mistake made in0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1S 3==b 1+b 3+b 5+b 7; Picture 231.1


48On the ground of values of these sums, it can be determined unambiguously, whetherthe mistake was made, and if so, the bad (altered) bit can be found.Task. A) Analyze the codes of Hamming, sums S 1, S 2, S 3and fill in the table above;B) Determine, if the encoded message 1100011 was transmitted correctly, and ifnot, restore the original coded message.232. Interest. A man went to borrow some money from a moneylender. The moneylenderagreed to lend and asked to repay money next month in the following way:on the first day of the month – 1 litas, on the second – two litas, on the third – fourlitas, i.e. every day to repay twice as much as the day before. On the day when the debtcould be paid off, the debtor would have to repay all rate of that day too. The overpaidsum would be the moneylender’s interest.A moneylender can lend not more than 30000 (thirty thousands) litas.Task. A moneylender reconsidered the situation and agreed to lend only if the loansum would be repaid in d days sharply, i.e. if in the way presented above it is notpossible to repay in other number of days.Write a program to calculate:a) how many litas it would be the most profitably to borrow for the man, i.e. whenthe interest in litas would be the least;b) how many litas it would be the most profitably to lend for the moneylender, i.e.when the interest in litas would be the biggest.Example. If number of days is 2, the most profitably for the man would be toborrow 3 litas, and the most profitably for the trader would be to lend 2 litas.233. Theorem 6174. Sequence 6174 is formed in the following way. The firstmember of the sequence is any tetra-signed number n 1. The only restriction: all fourdigits of this number can’t be equal (i.e. at least one must differ from the remainingthree). Two new numbers will be formed from the first member of the sequence. Thefirst number is obtained by sorting digits of n 1in descending order and the secondnumber will be obtained by sorting digits in ascending order. We subtract the secondnumber from the first one and obtain the second member n 2of the sequence. Againtwo new numbers are formed from n 2, the smaller is subtracted from the larger, thethird member of the sequence n 3is obtained, etc. Sequence is finished when its membersstart repeating (i.e. it can’t have two identical members). If the member of sequencehas less than four digits, then, sorting its digits (i.e. searching for further member),extra zero (or zeroes) is attached.Theorem 6174 states that the last member of the sequence formed in this way willalways be equal to 6174.Note: further members of the sequence will repeat, because 7641–1467==6174.Example: let us take the number 7815. It will be the first member n 1of the sequence:8751 – 1578 == 7173; n 2;7731 – 1377 == 6354; n 3;6543 – 3456 == 3087; n 4;


8730 – 0378 == 8352; n 5;8532 – 2358 == 6174; n 6;Task: The first member n 1of the sequence is given. Write a program to find thenumber of the last member (it is equal to 6174) of sequence.For example, if the input is 7815, the result should be equal to 6.49STAGE IIJUNIOR DIVISIONy 1X 3234. Parallel Sorting (theoretical task). Sequences of1 5 3 2 9 8numbers often have to be sorted in ascending or descendingorder. During the process of sorting, elements of sequencesPicture 234.1are compared andswapped. Sometimes theseX 1 y 1= min(x 1, x 2)actions can be performed inparallel. Consider the sequenceX 2 y 2= max(x 1, x 2)at picture 234.1.Two pairs of elementsPicture 234.2Picture 234.3can be compared andswapped at the same moment:x 1the second elementwith the fourth one and thefifth with the sixth one – thesorted sequence is obtained.Comparator is used inX 2y 2y 3algorithms of parallel sorting.It is a circuit having twoX 4y 4Picture 234.4inputs and two outputs (picture234.2: inputs are on theleft, outputs – on the right).X 1For example, whenx 1=3, x 2=1, we obtain situationin pict. 234.3.Comparators are joinedX 3with each other and so sortingnetworks are obtained.They sort members of sequencein ascending order. X 5Undoubtedly, not everysuch network sort sequence X 6completely Consider the exampleon pict. 234.4.Picture 234.53 11 3X 2 y 2y 3X 4 y 4y 1y 5y 6


50If inputs of network are equal to x 1=5, x 2=9, x 3=4, x 4=2, then outputs will beequal to: y 1=4, y 2=2, y 3=5, y 4=9.Task. Parallel sorting network is presented in the picture 234.5. The sequencebeing sorted is known too: x 1=6, x 2=5, x 3=4, x 4=3, x 5=2, x 6=1. Calculate the values ofy 1, y 2, y 3, y 4, y 5, y 6.235. Roman Numerals. Latin letters I, V, X, L, C, D, M, meaning numbers 1, 5, 10,50, 100, 500, 1000 accordingly, are used for writing Roman numerals. Value of a Romannumber is calculated in the following way: if the larger digit is before the smallerone or if two digits are the same, then they are added, and if the smaller digit is beforethe larger one, then the smaller one is subtracted from the larger digit. For example,MCXLIV == 1000 + 100 + 50 – 10 + 5 – 1 == 1144.These rules are not enough if one wants to find out how is the Roman numberbeing formed, but they can be used for convert Roman number into Arabic unambiguously.Assume, that the largest Roman number is MMMCMXCIX (3999).Task. Write a program to convert the given Roman number into Arabic.236. Three-digit Numbers. Given a sequence of digits. There is minus one (-1) atthe end of it. It does not belong to the sequence (it is not a digit), it just indicates theend of it. The sequence has not less than three members.Task. Write a program to calculate how many different three-number digits it ispossible to make each time taking 3 digits standing next to each other. Digits can notbe not exchanged; the first digit of number cannot be equal to 0.For example, if the input data are: 2 4 5 5 4 5 5 2 -1, the solution should be5, because five different three-digit numbers can be formed (245, 455, 554, 545, 552).STAGE IISENIOR DIVISION237. Parallel sorting (theoretical task). Sequences of numbers often have to besorted in ascending or descending order. During the process of sorting, elements ofsequences are compared and swapped. Sometimes these actions can be performed inparallel. Consider the sequence on pict. 234.1.Two pairs of elements can be compared and swapped at the same moment: thesecond element with the fourth one and the fifth with the sixth one – the sorted sequenceis obtained.Comparator is used in algorithms of parallel sorting. It is a circuit having twoinputs and two outputs (picture 234.2: inputs are on the left, outputs – on the right).For example, when x 1=3, x 2=1, we obtain situation in picture 234.3.Comparators are joined with each other and so sorting networks are obtained.They sort members of sequence in ascending order. Note that inputs and outputs of


any comparator can be only theadjacent elements of the sequencebeing sorted. Only one comparatorcan work with the same elementin parallel. Undoubtedly, not everysuch network sort sequencecompletely Consider the example:If inputs of network on the leftare equal to x 1=5, x 2=9, x 3=4, x 4=2,x 5=6, then outputs will be equal to:y 1=5, y 2=2, y 3=4, y 4=6, y 5=9.Let’s call all the comparations,performed in parallel (i.e. at theX 11 2 3 4žings. step žings. step žings. step žings. stepPicture 237.151y 1yX 22X 3y 3X 4X 5y 5same time) a step. Network is assumed to be more effective if number of steps is less.Task. Create a parallel sorting network to sort the sequence of four members completely.Number of steps must be the least.Represent this network in scheme, as it is shown in picture 237.1.238. Skyscraper. There are n offices, numbered from 1 to n in a new skyscraper.The table (-es) with the number of the office should be fastened to the door of eachoffice. Only one digit is written on one table. If the number of the office is not onedigitnumber, several tables should be fastened to each door.Task. Write a program to calculate the numbers of tables with each digit separatelyneeded to fasten numbers to the doors of all the offices.For example, if n==6, the output should be 0 1 1 1 1 1 1 0 0 0; here thefirst number means the needed amount of tables with digit 0, the second one meansthe amount of tables with digit 1 and etc. The last number means the amount of tableswith digit 9.239. Yang’s Table. Yang’s table consists of different natural numbers groupedinto the rows of non-increasing length, aligned left; members of each row increasefrom left to right, and members of each column increase downwards.There exists an algorithm to update Yang’s table a new element (number). Considerthe example in picture 239.1.The Yang’s table above must be updated with the new element 8.We do the following: write 8 to theplace of number 9 being in the first row,because 9 is the smallest number of thisrow greater than 8. Now number 9 is“pushed” to the second row, where itreplaces number 10. This one “pushes”13 from the third row to the fourth one.1 3 5 9 12 162 6 10 154 13 141117Picture 239.1y 4


52Because there is no number, greater than 13, 1 3 5 8 12 16it is left at the end of this row and the processis over. We obtain the updated Yang’s2 6 9 154 10 14table (picture 239.2).11 13If there is such a need, the number of17rows is increased.Task. Write a program to add a new numberto Yang’s table in the way, described above and print this updated table.Picture 239.2Input. The first line of the input file contains the number of rows n (1≤n≤10) of thetable and the number sk that must be inserted. In the further n lines Yang’s table is written.Each of those lines ends with zero. Number of columns in the table does not exceed 10.Examples:InputOutput5 81 3 5 9 12 16 0 1 3 5 8 12 162 6 10 15 0 2 6 9 154 13 14 0 4 10 1411 0 11 1317 0 17STAGE IIIPART IJUNIOR DIVISION240. Crossing the Channel. On one shore of the channel a lot of levees are set out.They are situated one after another and numbered from 1 to N. The distance betweentwo next levees is one kilometer.On the othershore of the channelstraight in front of the firstlevee a boatman waits. Heshould reach the Nthlanding place in the shortesttime.The boatman can sailto any levee, and then, ifthere is such a need, he1 km 1 kmcan ride the remaining1 2 3 ... Ndistance by bicycle. It isknown the average speed Picture 240.1


of the boat and of the bicycle as well as the width of the channel. The speed of flow ofwater is small, so simply ignore it.Task. Write a program to determine from the given data the number of the leveethe boatman should sail so that he would reach the Nth levee in the shortest time. Ifseveral variants are possible, output any one of them.Input. Four integers are written in the first and the only line of the input file:number of levees N, the width of the channel D (in meters), the average speed of theboat U and the average speed of the bicycle V (in meters per hour).These limits stands: 1 ≤ N ≤ 1 000 000, 10 ≤ D,U≤ 10 000, 10 ≤V≤ 20 000.Output. One integer M (1≤M≤N)Example– the number of the levee the boatmanshould sail to – should beInputOutput3 10 1000 500 3printed to the screen.241. Patterns. We will call the pattern a string which consists of some of thefollowing symbols: capital and small Latin letters, digits, asterisks (*) and questionmarks(?). Asterisk stands for any sequence of letters and/or digits (the empty sequenceis possible too), question-mark stands for any one letter or digit.Obviously, one can get a lot of various strings from one pattern, for example,strings 00c001BRABA, BRACA, vBRA1A and etc. applies to the pattern *BRA?A,but strings BRaCA, xBRATKA and etc. do not apply to this pattern.We have two patterns. If any string which applies to the first pattern, applies to thesecond one too, and if any string which applies to the second pattern, applies to thefirst one, these patterns are considered to be equivalent.Task. Given two patterns. Write a programto test if these two patterns are equivalent. Example 1Input. Input file consists of two lines. InputOuputThe first line contains the first pattern (sequenceof symbols without spaces). The bra***abra*a YESsecond line contains the second pattern (sequenceof symbols without spaces). Each Example 2pattern can contain from 1 to 250 symbols. InputOutputOutput YES to the output file if the patternsare equivalent, and NO otherwise.br??a*a NObr?a***a53STAGE IIIPART ISENIOR DIVISION242. Patterns. We will call the pattern a string which consists of some of thefollowing symbols: capital and small Latin letters, digits, asterisks (*) and question-


54marks (?). Asterisk stands for any sequence of letters and/or digits (the empty sequenceis possible too), question-mark stands for any one letter or digit.Obviously, one can get a lot of various strings from one pattern, for example,strings 00c001BRABA, BRACA, vBRA1A and etc. applies to the pattern *BRA?A,but strings BRaCA, xBRATKA and etc. do not apply to this pattern.We have two patterns. If any string which applies to the first pattern, applies to thesecond one too, and if any string which applies to the second pattern, applies to thefirst one, these patterns are considered to be equivalent.Task. Given two patterns. Write a program to test if these two patterns are equivalent.Input. Input file consists of three lines. The first line contains two integers: lengthsof the first and of the second patterns L 1and L 2. Each pattern can contain from 1 to500 symbols: 1≤L 1,L 2≤500.The second line contains the first pattern(sequence of L 1symbols without spaces); thethird line contains the second pattern (sequenceof L 2symbols without spaces).Output YES to the output file if the patternsare equivalent, and NO otherwise.243. Housepainter. Housepainter who redecorates flats, signed a big contract forthe following month. He divided everything into N separate jobs. However some jobsare interdependent, that is, particular job can be started only if some other one or severaljobs are done. For example, walls can be painted only after they are daubed and primed.If job a should be done before starting job b, then we will say that jobs a and bmake an interdependent pair.The set of jobs is correct, i.e. there is no such chain of interdependent pairs of jobsthat would make a cycle.Task. It is known the number of jobs and the pairs of interdependent jobs. Write a program,to determine the order of performing jobs. The succession of jobs should be such thatthe job a must be done before job b, if only jobs a and b make an interdependent pair.If several solutions are possible, find any one of them.Input. The first line of the input file contains two integers N and P. Where N is thenumber of jobs (1≤N≤250), P is the number of interdependent pairs. It is assumed thatjobs are numerated from 1 to N.In each of the remaining P lines there are written two integer a and b (1≤a,b≤N). Thesenumbers mean that jobs aand b compose an interdependentpair, i.e. that jobb can be started only afterthe job a is finished.The same interdependentpair can only be metonce in the input.ExampleInputOutput5 7 YESbra*abra***aExampleInput Output Other possible solutions4 4 4 4 44 2 3 2 33 1 2 3 14 3 1 1 24 1


Output. N integers (numbers of jobs must sorted in the order of their performance)– should be written to the output file, one number per line.55STAGE IIIPART IIJUNIOR DIVISION244. Slips With Numbers. The following experiment is carried out. There aretaken N numbered paper slips and any natural number from 1 to 100 is written oneach slip. Written numbers can repeat. All the slips are thrown to some box.Then two randomly selected slips are taken from the box. Their numbers (not thenumbers written on them!) and the sum of the numbers written on the two slips arewritten down. Then the first slip is thrown away, and the second one is put back to thebox. The action is repeated until only two slips remain in the box.When the last two slips remain in the box, the product and the sum of the numberswritten on the slips is calculated and noted down. The numbers of the slips are notmentioned. The experiment is over with it.Task. Write a program, which, according to the notes of experiment, would determinewhich number, was written on each slip.If several solutions are possible, find the one where the number written on the firstpaper slip is the least.Input. The first line of the input file contains the number of slips N, 3≤£N≤£10000.In the remaining N-2 lines there are written three numbers per line.The first one is the number of the first slip (which is thrown away later) from the firstdrawn pair, the second one is the number of the second slip from the same pair (which isput back to the box), and the third number is sum of numbers written on these slips.In the next line there are written data about the second drawn pair of slips, in thenext other line there are written data about the third pair and etc.In the last two lines (in the Nth and in the N+1) of the input file there are writtenthe product and the sum of numbers, written on the last two slips.Output. The output file must contain N lines, one number per line. Write the numberwritten on the first slip to the first line, the number written on the second slip to thesecond line and etc.ExampleInput Output Explanation5 102 1 40 304 3 70 303 5 90 40600 6070After drawing the first pair the sum 40 is obtained(30+10=40).After drawing the second pair the sum 70 is obtained(30+40=70). After drawing the third pair the sum 90 isobtained (30+60=90). The product of the last two leafletsis equal to 600 (60´´10=600), and their sum is 70(60+10=70).


56245. Picture. A child has a lot of coloured rectangular slips of paper and a rectangularboard. The board is divided into unitary squares and it has size of N´´M. Thesizes of slips are such that each slip can be divided into unitary squares.A child spreads slips on the board. Slips are aligned with the squares of the board.Positions of slips on the board are indicated by coordinates of two opposite angles(row and column). Slips are spread on the board in turn. The newly put slip can newlycover squares already covered by other slips.If none of the slips cover the square, it is assumed to be colourless, if one or moreslips cover it, then the colour of square is coincident with colour of the uppermost slip(i. e. this slip was put down the last).It is possible to get from one square of the board to another, if only these squareshave a common edge. Squares of the same colour belong to the same uni-colouredshape, if it is possible to get from one square to another one without crossing squaresof any other colour. Uncovered (colourless) squares cannot make a shape (i.e. we arenot interested in colourless shapes).Task. Write a program to determine how many uni-coloured shapes there are onthe board, which of them is has the largest, and what is the area of that shape.Input. In the first line of the input file there are written three integers. They are thesize of the board N (number of rows) and M (number of columns), 1≤N,M≤1000 andthe number of leaflets L, 1≤L≤1000. Rows are numerated downwards; columns arenumerated from left to right.In the remaining L lines there are data about L leaflets in the order of their placingon the board. Each line contains the colour of the slip (small Latin letter) and thecoordinates of the upper left and of the right bottom corners (row, column) accordingly.There is left one space between numbers or between a number and a letter.None of the slips goes out of the limits of the board, and there are no slips havingarea equal to zero.Output should be written to the first line of the output file. Firstly output the totalnumber (integer) of uni-coloured shapes, then write the colour of the largest unicolouredshape (Latin small letter), the area of the this shape (an integer) and thecoordinates (row and column) of any square, which belongs to that shape. Leave onespace between numbers or between a number and a letter.If several solutions are possible, output any one of them.ExampleInput Output Comments14 14 7r 3 5 10 8g 1 1 9 3j 2 2 4 6r 7 3 11 7g 6 7 8 12m 8 2 13 4r 2 10 6 116 r 27 3 7 Picture below corresponds to thisexample.


1 2 3 4 5 6 7 8 9 10 11 12 13 141 g g g2 g j j j j j r r3 g j j j j j r r r r4 g j j j j j r r r r5 g g g r r r r r r6 g g g r r g g g r r g7 g g r r r r g g g g g g8 g m m m r r g g g g g g9 g m m m r r r r10 m m m r r r r11 m m m r r r12 m m m13 m m m1457246. Numbering of Town Residents. The mayor of one town decided to number all theresidents of his town. He ordered to make N tokens and to cut numbers from 1 to N on the eachof them. The he asked his secretary to send them by post to all the residents. Unfortunately, thesecretary was very absent-minded and made a lot of mistakes – most of the residents receivedtokens with wrong numbers. Because all the residents knew their numbers, they decided toexchange tokens so that each would get a token with his number after exchange.The residents exchange tokens only in pairs, i.e. two residents make an agreementand exchange their tokens. Two residents can only exchange tokens, if at least one ofthem receives his own token after exchange. Each resident can exchange a token oncea day, but different pairs of residents can exchange tokens on the same day.Residents, who have tokens with their own numbers (or who received them afterexchange), do not take part in exchanges any longer.Task. Write a program to calculate the minimal number of days necessary for exchangesso that all the residents would get tokens with their own numbers.Input. The first line of the input file contains the number of residents of the town N(2≤N≤10000).Each of the followinglines containone numberper line – numberof token the correspondingresidentreceived bypost.So, the secondline containsthe number of to-ExampleInput Output Comments62341562 P.s. X(Y) in the comments means that residentwhose number X, has got a token with number Y.On the first day it is exchanged like this:1(2)↔2(3); 3(4)↔4(1);The situation after these swaps is as follows:1(3), 2(2), 3(1), 4(4), 5(5), 6(6);So on the second day the first and the thirdresidents have to exchange their tokens:1(3)↔3(1);


58ken the first resident got (he should have received a token with number 1). The third linecontains the number of token the second resident received, etc.Output the minimal number of days, necessary to exchanging tokens to the firstline of the output file.247. Cakes. There are N kinds of cakes of in the confectionery. The amount ofcakes of each kind is limited. The client wants to buy exactly K – we will call it thepurchase. In the purchase there can be several cakes of the same kind (of course, notmore than there are cakes of that kind in the confectionery), some kinds of cakes maynot be included into purchase. Two purchases are different, if there exist at least onekind of cakes where the amount of this kind of cakes in the two purchases differs.Task. Write a program to find all possible different purchases of the cakes.Input. The first line of the input file contains one integer K (1≤K≤30), which is thenumber of cakes in the purchase. In the second line there is written one integer N(1≤N≤30), the number of different kinds of cakes in the confectionery. It is assumedthat all kinds of cakes are numerated from 1 to N.The remaining N lines contain one number per line, indicating how many cakes ofappropriate kind there are in the confectionery, that is, in the first of the remaininglines there is written number of cakes of the first kind, in the second line there iswritten number of cakes of the second kind and etc.In the input data K and N will se such that given run time limit will be enough togenerate ALL sets of N kinds of cakes having size K.Output the amount of possible different purchases P to the first line of the output file.Further there should be P lines, indicating purchases, one line per purchase. Eachline should contain N numbers separated by spaces and indicating how many cakes ofcorresponding kind there are in the purchase (if the purchase does not contain cakesof some kind, 0 must be written).If K cakes can not be bought in any possible way, then 0 must be written in the first(and the only) line of the output file.ExampleInput Output Comments3 3Three cakes (K=3) compound the purchase; There2 0 3 two kinds of cakes in the confectionery (N=2): there are2 1 2 2 cakes are of the first kind and 10 cakes of the second10 2 1 kind.3 different purchases are possible:• 3 cakes of the second kind• 1 cake of the first kind and 2 cakes of thesecond kind• 2 cakes of the first kind and 1 cake of thesecond kind.


248. Boxes. There are N boxes of various sizes. The box is indicated by its width,length, and height. Width of walls is zero for all boxes. Boxes can be opened fromthe top and they are all empty.All N boxes must be conveyed. Number of trucks necessary for portage willdecrease if smaller boxes are be put into the bigger ones. Boxes can be turned whenputting one box into another. After putting smaller box into bigger one, it should bepossible to close the bigger oneThe boxes will be put one into another in the way of „matrioshka“, i.e. it will notbe possible to put into a bigger box several smaller boxes next to each other or one onanother.„Matrioshka“ is the national Russian toy-doll. When we open it, we find another dollin it. And when we open that doll, we again find a smaller doll inside. And so on, until wefind the last, the smallest doll, which does not open, i.e. there is no doll inside it.Task. Write a program to pack boxes in the way of „matrioshka“. The total numberof „matrioshka“s (i.e. the total final number of separate boxes) should be minimal.Input. The first line of the input file contains the number of boxes N (2≤N≤100).Boxes are numbered from 1 to N.In the remaining N lines there are written the sizes of the boxes, one line per box.In each line there are four integers: the number of the box nr, the width of the box w,59Example:Input Output Comment241 4 4 466 16 20 17 13 21 The output on the left is possible correct2 11 15 20 4 3 2 18 22 output for the given input. However the3 9 9 9 14 1 15 7 5 9 toral number of „matrioshka“s is not4 4 2 2 12 10 8minimas5 22 19 36 19 24 116 2 2 2 237 14 14 258 126 25 509 50 50 5010 14 14 2511 11 15 2012 4 2 213 22 19 3614 2 2 215 9 9 916 4 4 417 14 14 2518 22 19 3619 2 2 220 9 9 921 126 25 5022 50 50 5023 4 2 224 4 4 4


60the length l and the height h. The restrictions are: 1≤w,l,h≤500, all three dimensionsare expressed in centimetres.Output. The first line of the output file should contain the total number of„matrioshka“s M (the total number of separate boxes). The remaining M lines shouldcontain descriptions of „matrioshka“s, one line per „matrioshka“.The line describing one „matrioshka“ should contain the numbers of boxes thatmatrioshka contains. The numbers of the boxes should be presented in increasing orderof the box sizes. I.e. the line should be started with the smallest box numbers (i.e. thereare no boxes in it) and should be finished with the largest one (the outside box).During evaluation the points will be given taking into account the best result fromthe contestants programs.STAGE IIIPART IISENIOR DIVISION249. Slips With Numbers. The following experiment is carried out. There aretaken N numbered paper slips and any natural number from 1 to 100 is written oneach slip. Written numbers can repeat. All the slips are thrown to some box.Then three randomly selected slips are taken from the box. Their numbers (not thenumbers written on them!) and the sum of the numbers written on the two slips arewritten down. Then the first slip is thrown away, and the second and the third slips areput back to the box. The action is repeated until only two slips remain in the box.When the last two slips remain in the box, the product and the sum of the numberswritten on the slips is calculated and noted down. The numbers of the slips are notmentioned. The experiment is over with it.Task. Write a program, which, according to the notes of experiment, would determinewhich number, was written on each slip.If several solutions are possible, find the one where the number written on the firstpaper slip is the least.Input. The first line of the input file contains the number of slips N, 3≤N≤10000.In the remaining N-2 lines there are written four numbers per line.The first one is the number of the first slip (which is thrown away later) from thefirst drawn triplet, the second and the third numbers are the numbers of the other twoslips from the same triplet (which are put back to the box), and the fourth number isthe sum of numbers written on these three slips.In the next line there are written data about the second drawn triplet of slips, in thenext other line there are written data about the third triplet and etc.In the last two lines (in the Nth and in the N+1) of the input file there are writtenthe product and the sum of numbers, written on the last two slips.


Output. The output file must contain N lines, one number per line. Write the numberwritten on the first slip to the first line, the number written on the second slip to thesecond line and etc.ExampleInput Output Comment52 4 5 1304 3 1 803 5 1 100600701030304060After drawing for the first time the obtainedsum is 130 (30+40+60=130). After the secondtime the obtained sum is 80 (30+40+10=80).After the third drawing the sum is 100(30+60+10=100).Product of the last two slips is equal to 600(60×10=600), and the sum is equal to 70(60+10=70).61250. Engineering Preparation. It is the second day on the training ground. Cadetsare taught to lay anti-tank mines manually. Sergeant R. supplied cadets with amap and several mines. These mines should be carried in bags to the objects thatshould be mined. Anti-tank mine TM-72 weights several kilos.Cadets have to mine the territory. The map of the territory is divided into unitarysquares. The territory corresponding a unitary square in the map will be called a field.The field can contain some object or it can be empty. Objects can be of two kinds:• P-object; i.e. this object should be protected from possible attacks;• N- object; i.e. this object is not important; enemies will be able to movethrough the fields with N- objects without any loss.Objects are situated so that eight fields surrounding each object (M-object and N-object) are empty. Only empty fields can be mined (one mine per field).Enemy tanks can move from one field to another if squares corresponding to fieldsadjoin edges or corners on the map. Enemies can move without any loss in not minedfields only.BBBAAAa) b) c)Picture 250.1


62Let us analyse three examples. Enemy has come to the field A and he wants tooccupy the object in the field B.In the case a), enemy can move from A to B without loss. In cases b) and c) it isnot possible to do this without loss.It is assumed that enemy camp is outside the map. I.e. during attack the enemyfirst will get into some (not known which in advance) marginal field.Task. Cadets had analysed the map and estimated the situation: all P–objects aresituated so close to each other, that it is enough to surround them with one curve (itshould divide the plane into two pieces) of mines. Write a program to calculate thesmallest number of mines necessary to protect all P-objects, i.e. to surround themwith a curve of mines.Input. The first line of the input file contains two integers: numbers of rows (N),and columns (M) in the map, i.e. the size of the map. Restrictions: 3££N,M££100.The remaining lines determinate the map. In each of the remaining N lines thereare written M symbols. The following symbols are possible:X – P-object;1 – N-object;0 – empty field that can be mined;Output. The smallest number of mines necessary to protect all P-object should bewritten to the first and only line of the output file.ExampleInput Output Comments10 11000000000000100X0000000000000000000X010000000000000X00000X00100000000000000000000X001000000000000000000000000030000***00000010*X*000000***0*000000*X01****000*00000X*000*X001***000***0**0000000*X*01000000***0000000000000000

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!