You've been given the unfortunate task of planning textbook wrapping for your brothers and sisters (still in highschool). To save money, your parents bought sufficient plastic covering for any concievable number of text books (certainly enough for all of the wrapping you will be asked to do).
The plastic comes in a huge roll (which is guaranteed to be long enough) 1,8m wide. Your parents have also insisted that you plan the book covering so that a stretch of the roll will be cut off straight (meaning that the cut line will be at 90 degrees to the edges). To save time, you will be wrapping each book with a rectangular piece of plastic  in particular, you will not be making any further cutouts to beautify the wrapping.
Given the n textbooks to be covered, your task is to determine the mininum length k (in millimeters) of plastic to cut from the roll, so that each book is covered with a 4cm wraparound (perhaps with some wasteage). Each of the n books has the usual shape for books (rectangular, and having both front and back covers) and is described using an ordered sequence of three integers (measured in millimeters): the height, width, and thickness. All except the thickness are guaranteed to be positive. (The thickness may, in fact, be zero in the case that you are asked to cover a leaflet.) You are guaranteed never to have a book with a dimension greater than 1720mm.
Your input will contain of several datasets, each of them consisting on a sequence of lines: the first line contains n; each of the n subsequent lines (terminated by a newline) contains three ordered integers (separated by a space) describing the height, width and thickness of one of the books to be covered.
For each dataset, your output will consist of integer k on a line by itself.
2 620 500 0 610 300 400
1080
______________________________________________________ 2001false
You have been asked to create a code generator for a simple machine. The input to the code generator (produced by the compiler's frontend) consists of arithmetic expressions in postfix form (also known as postorder or reverse Polish notation form). The output will be in the assembly language of the target machine.
The target machine has a single register and a number of temporary locations (which are allocated by the assembler  something beyond the scope of this problem) named $1, ... , $9 (to be used in that order). The machine supports the following instructions, where the operand is either an identifier (identifiers consist of single letters  either upper and lower case) or a temporary location:
The arithmetic operators replace the contents of the register with the expression result.
The input consists of several test cases, each on a line by itself. Each test case contains a single, wellformed (and nonempty), postfix ex pression appearing on one line with no whitespace (no spaces, tabs, newline characters, etc.). The operators include the normal ones `+', `', `*', `/' and `%' (for remainder).
The output of each test case will consist of a sequence of lines each with a single instruction, satisfying the following:
Your code generator must create straightforward code, without any optimizations whatsoever. Print a blank line betwee consecutive test cases.
AB+CD+EF++GH+++
L A A B ST $1 L C A D ST $2 L E A F A $2 ST $2 L G A H A $2 A $1
______________________________________________________ 2002false
In an effort to entertain your crosswordobsessed aunt and uncle, you decide to work on some software to create compact crosswords. A crossword must be rectangular and adjacent letters must be part of a word. the meaning of `adjacent' differs for the two different types of crosswords  see below. This problem is casesensitive.
There are two types of crosswords:
You are given a sequence of n words along with possible synonyms (meaning equivalents) for that word  no word will appear more than once anywhere in the input. With this, you are to determine the minimum number k of black squares which must be present in a crossword for the words. Each word, or a synonym thereof, must appear exactly once in the crossword and no additional words may appear.
The input consists of several test cases. The first line of each test case contains either the letter S or the letter D (designating whether you are to consider strict or diagonal crosswords). The next line contains positive integer n. The next n lines (each terminated by a newline) each consist of at least one word, followed by a number indicating the number of synonym words for the first word on the line, then the list of synonym words, each separated by a space.
The output for each dataset consists of k followed by a newline.
Note for the sample output: since `copter' and `poll' can be intersected at either
the `o' or the `p', in both
cases giving a
5 x 4 crossword with
4^{ . }5  5  4 + 1 = 12.
S 2 Helicopter 1 copter election 1 poll
12
______________________________________________________ 2003false
Genomic computing has become big business, and you decide to cash in. Your first attempt is to write a program which constructs a family tree from genetic information.
The gene sequence for an individual is given as a string (with no spaces) consisting of only the letters a, c, g, and t. The relatedness of two individuals can be estimated using the Hamming distance between their gene sequences. The Hamming distance between strings x and y is the number of individual letters in x which must be changed to give y. For Hamming distance purposes, you are guaranteed that x and y are the same length.
You may assume that each individual has either zero or two offspring, and that this species functions asexually (each individual has at most one parent). We are interested in a family tree in which we minimize the Hamming distance between a parent and its children.
Given n : n > 0 individual gene sequences, you are to determine a plausible family tree which has the smallest total Hamming distance h (the sum of the Hamming distances between all parents and their children). Your output must include the family tree. If there is more than one such tree, output any of them.
The input for each dataset consists of several lines. The first line contains n. Each of the following n lines contains a single individual's gene sequence.
The output for each dataset consists of n + 1 lines. The first line contains h. The remaining lines contain the family tree in prefix form. Each line contains a single individual, followed by a space and either the letter P (if the individual is a parent) or the letter N (if the individual is not a parent). When there are two children, output them in any order.
3 gattaca gcttaca gaccata
4 gattaca P gaccata N gcttaca N
______________________________________________________ 2004false
Your city's fire department collaborates with the transportation depart ment to maintain maps of the city which reflects the current status (on that day) of the city streets. On any given day, some streets are closed for repairs or construction. The fire engine navigator needs to be able to select routes, from the firestation to the fire, that do not use closed streets. You must write a program that the central dispatcher can use to generate routes from the firestation to a fire.
Street intersections are identified by positive integers not more than 20, with the firestation always at intersection 1.
The input file contains several dataset. The first line of each dataset consists of a single integer which is the number of the street intersection closest to the fire. The following lines each consist of a pair of positive integers separated by a space and terminated by a newline. They represent the adjacent street intersections of an open street. For example, if 4 7 appears on a line, then the street between intersections 4 and 7 is open and there are no other intersections between 4 and 7 on that section of street. The final line of each dataset consists of a pair of 0's.
For each dataset, your output must consist of a line for each valid route from the firestation to the intersection closest to the fire, written with the intersections in the order in which they appear on the route. The intersections must appear separated by a space, terminated by a newline. Include only routes which do not pass through any streetintersection more than once. The lines of output must be in lexicographical order. Print a blank line between consecutive datasets.
6 1 2 1 3 3 4 3 5 4 6 5 6 2 3 2 4 0 0
1 2 3 4 6 1 2 3 5 6 1 2 4 3 5 6 1 2 4 6 1 3 2 4 6 1 3 4 6 1 3 5 6
______________________________________________________ 2005false
You are to implement a message decoder for a scheme which sends mes sages in two parts: a header and the encoded message itself.
The foundation of the scheme is a sequence of binary `key' strings as follows:
The first one is of length 1, the next three of length 2, the next seven of length 3, next fifteen of length 4, etc. If two adjacent keys have the same length, the second can be obtained from the first by adding 1. Note that there are no keys consisting only of 1s.
The keys are mapped to the characters in the header in order. Suppose the header is Bruce, the first key (0) is mapped to B, etc.
The encoded message contains only 0s and 1s and possibly carriage re turns (newlines)  though they are to be ignored. The message is divided into segments. The first 3 digits of a segment give the binary representation of the length of the keys in that segment. For example, if the first 3 digits are 011_{2}, then the remainder of the segment consists of keys of length 3_{10} (one of 000, 001,..., 110). The end of a segment is a string of 1s which is the same length as the length of the keys in that segment (this is why all 1s were not used above). So, in the example above, the segment would be terminated by 111. The entire message is terminated by a segment begining 000 (which would signify a segment in which keys have length 0). The message is decoded by translating the keys in the segments into the header characters to which they have been mapped.
The input file contains several datasets. The first line of each dataset contains the header, terminated by a newline (which is not part of the message); any spaces are part of the header. The length of the header is limited by the fact that key strings have a maximum length of 111_{2} (7_{10} in decimal). If there are multiple copies of a character in the header, then several keys will map to that character.
The remaining lines of input contain the encoded message. The message is made up only of 0's and 1's (and possibly carriagereturns  to be ignored). You are guaranteed that it is a valid message according to the encoding described above.
For each dataset, your output must consist of the message, followed by a newline.
$#**/ 01 00000 1011011 000111 00101000
##*/$ ______________________________________________________ 2006falseWrite a program to find the most frequent word in a file of text. A word is any nonempty continuous sequence of alphabetic characters. Case is not regarded as significant, so the words "bother" and "BOTHeR" should be considered the same word.
Any nonalphabetic characters (including control characters such as newlines) can be used to separate words. Thus "isn't" is counted as two words, the second of which is a one letter word consisting only of the letter "t".
If more than one word appears with the maximum frequency, then the first word to reach the maximum frequency is required.
Input
Input will consist of a set of paragraphs each terminated by a single line containing only the character '#' which will not otherwise occur anywhere in the text. No paragraph will contain more than 2000 different words, and no word will be more than 20 letters long. The input is terminated by a test case with no words at all. This case should produce no output.
Output
For each paragraph, your program should print one line containing the frequency of the most frequent word, right justified in a field of width 4, followed by a space and the most frequently occurring word itself, entirely in lower case.
Sample Input
This is a simple file of test data, which should not cause your program any trouble. Do note that it contains several punctuation characters. Of course, this is not really a problem, because such characters are treated in the same way as spaces. # Don't use contractions; it isn't nice. # aBc def AbC def dfe ABC # 123 #Sample Output
2 of 2 t 3 abc______________________________________________________ 2007false
Markup languages such as HTML use tags to highlight sections with special significance. In this way, a sentence in boldface can be indicated thus:
<B>This is a sentence in boldface</B>
Typically every tag has an opening tag of the form <TAG> and a closing tag of the form </TAG>, so that portions of text can be bracketed as above. Tags can then be combined to achieve more than one effect on a particular piece of text simply by nesting them properly, for instance:
<CENTER><B>This text is centred and in boldface</B></CENTER>
Two of the most common mistakes when tagging text are:
Write a program to check that all the tags in a given piece of text (a paragraph) are correctly nested,and that there are no missing or extra tags. An opening tag for this problem is enclosed by angle brackets, and contains exactly one upper case letter, for example <T>, <X>, <S>. The corresponding closing tag will be the same letter preceded by the symbol "/". For the examples above these would be </T>, </X>, </S>.
The input will consist of any number of paragraphs. Each paragraph will consist of a sequence of tagged sentences, over as many lines as necessary, and terminating with a # which will not occur elsewhere in the text. The input will never break a tag between two lines and no line will be longer than 80 characters. The input will be terminated by an empty paragraph, i.e. a line containing only a single #.
If the paragraph is correctly tagged then output the line "Correctly tagged paragraph", otherwise output a
line of the form "Expected <expected> found <unexpected>" where <expected> is the closing tag matching
the most recent unmatched tag and
The following text<C><B>is centred and in boldface</B></C># <B>This <\g>is <B>boldface</B> in <<*> a</B> <\6> <<d>sentence# <B><C> This should be centred and in boldface, but the tags are wrongly nested </B></C># <B>This should be in boldface, but there is an extra closing tag</B></C># <B><C>This should be centred and in boldface, but there is a missing closing tag</C># #
Correctly tagged paragraph Correctly tagged paragraph Expected </C> found </B> Expected # found </C> Expected </B> found #
______________________________________________________ 2008false
The Department of Defence of a certain country (No, not Australia or New Zealand), in conjunction with the Department of Police, have devised a brilliant method of saving money on crowd control  really bouncy rubber bullets. They had noticed that the rubber bullets they had been using were largely being wasted  those that hit anyone or anything usually just fell to the ground, whereas if they were really, really bouncy, they would bounce off and possibly hit several more people before their energy was spent.
They decided to test this idea by building a special circular test rig. The bullet would be fired into the rig horizontally and at some predetermined angle to the tangent to the rig at that point. It would have sufficient energy to travel some considerable distance before stopping. (You may assume cartoon physics, i.e. that it travels horizontally until it reaches the end of its travel, at which time it drops to the floor.) However, as so often happens with lucrative defence contracts, the contractor made off with the money, so they decided to simulate the whole process on a computer. This is where you come in.
Write a program that will read in details of a test rig and a series of test firings and determine how many times the rubber bullet would bounce before it stops. You may assume that the bullet is a point and that, because of problems in determining the exact sequence of events, any test firing where the bullet stops within 1 mm of the rig is deleted from consideration.
Input will be a series of tests, each test consisting of a series of test firings. Each test starts with an integer specifying the radius of the test rig in millimetres and a value of 0 for the radius terminates the input. Each test firing occurs on a line by itself and consists of a distance in millimetres (between 100 and 10000 inclusive) that the bullet will travel, and an angle, in degrees, (between 10 and 170 inclusive, where 90 means directly towards the centre of the rig). The series of test firings will be terminated by a line containing two zeroes (0 0).
For each test rig, output a line with the words "Test Rig" followed by a space and then the number of the test rig (a running number starting at 1) followed by a series of lines, one for each test firing for that rig with each line giving the number of times a bullet bounces off a wall before it stops. This number is to be written without any leading or trailing spaces. A blank line should appear between test rigs. Follow the example given below.
100 1000 23 1200 47 0 0 0
Test Rig 1 12 8
______________________________________________________ 2009false
Lazy Larrys Leisure Photo Shop specialises in taking shots of people in leisure situations  at the beach, skiing, in cable cars and so on. When the photographer returns to the office at the end of a shoot, she has anything up to 50 images which she wishes to display. She has found that the most practical solution is to lay them out in a single row in a strip across the top of the screen with the first image hard up against the left of the strip, the rest of the images in order from left to right, and the last image as far right as necessary or possible.
Input will be a sequence of problems, terminated by a line of three (3) zeroes (0 0 0). The first line of each problem has three positive integers specifying WIDTH, SPACING, and NIMAGES. WIDTH is the width of the available screen area in pixels, SPACING is the maximum spacing to be used between images and NIMAGES is the number of images to be placed. This is followed by NIMAGES integers specifying, in order, the widths of the images, on one or more lines. You may assume that SPACING ≤ 10, that 0 < NIMAGES ≤ 50 and that the image widths range from 10 pixels to no more than WIDTH/2.
Output for each problem is a line with the words Problem number followed by a space and the problem number followed by a line containing either the word IMPOSSIBLE if placement is impossible, or NIMAGES integers, separated by single spaces, specifying the position at which the leftmost pixel of each image (in the order given in the input) should be placed. Pixels are numbered from 0 to WIDTH1.
380 8 5 35 28 43 35 5 0 0 0
Problem number 1 0 43 79 130 173
______________________________________________________ 2010false
Many sports and games hold tournaments to determine at least a winner and, very often, a ranking or ordering as well. In two player games (such as Tennis, Chess and Scrabble), the two most common forms of tournament areknockout (usually based on an initial ranking or seeding) and round robin (where everybody plays everybody else). The disadvantage in knockout is that a promising newcomer could meet a very much stronger player early in the tournament and not reach their true position. Round Robin eliminates this but at a huge cost in time  a Round Robin involving 128 players needs 127 rounds whereas it would take only 7 rounds in a knockout competition.
An alternative known as Swiss Draw is very popular in games such as Scrabble. To maximize competition, any one player will play any other player no more than once. After each round, players are ranked on the number of games they have won, where a draw is equal to half a win (more is better) and, within that, by spread  the cumulative difference between their scores and their opponents scores (again bigger is better). If by chance two or more players tie in this ranking then they appear in inverse order of their previous ranking, i.e. the initially lowerranked players move ahead. In each round each player either plays someone above them or the highest ranked player below them that allows everyone to play someone they have not played before. The input will specify the (usually random) ordering before the first game.
Write a program to determine the final ranking of a group of Scrabble players, given the initial draw and the scores for each individual for each round.
Input will consist of one or more scenarios. The first line of each scenario will consist of two integers, P and R, (16 ≤ P ≤ 64, 4 ≤ R ≤ P/4) denoting the number of players (a multiple of two) and the number of rounds respectively. This will be followed by P lines, each line consisting of a name (a string of 1 through 20 alphabetic characters without any spaces) followed by R integers (separated from each other and the name by at least one space) representing the R scores for that individual. The list will be in the initial order of play, thus in the first round player 2n+1 played player 2n+2 (0 ≤ n < P / 2). Input will be terminated by a line containing two zeroes (i.e. P and R both zero).
Output will consist of a list of all the players ranked according to the above criteria, together with the number of wins and the spread. Note that a draw is counted as half a win, so indicate an odd number of draws by a plus sign (+) after the number of wins. The name is left justified in a field of width 20, the number of wins is right justified in a field of width 3, specification of draws occupies 1 character position and the spread is right justified in a field of width 6. Leave one blank line between scenarios.
16 4 Absalom 280 334 319 426 Betsheba 374 514 459 417 Carolyne 318 415 445 481 Davidian 402 361 375 278 Eleanor 425 302 447 522 Frances 425 513 306 327 Gabriel 330 337 365 398 Hermione 539 254 442 450 Ishmael 485 305 540 522 Jeremiah 288 295 367 476 Kenneth 532 304 452 445 Laurence 426 437 260 474 Meredith 438 489 274 475 Nicholas 307 357 380 482 Octavia 426 498 305 497 Patricia 333 253 370 412 0 0
Ishmael 4 619 Meredith 3 247 Carolyne 3 186 Betsheba 3 158 Kenneth 3 126 Eleanor 2+ 11 Hermione 2 264 Laurence 2 93 Nicholas 2 114 Davidian 2 150 Frances 1+ 119 Octavia 1 85 Absalom 1 187 Jeremiah 1 188 Gabriel 1 338 Patricia 0 315
______________________________________________________ 2011false
Calypso is a funfilled family card game that has been propagated at the training camps for the Australian Maths Olympiad teams. The game is designed for four players and will be described in that way, although I am sure you can adapt it to a different number. I will start with a complete description, since I suspect most of you will never have heard of it and you may want to play it some time (possibly with your coach as a fourth on the way to Vancouver next year).
The game is played with a standard deck of 52 cards where each card has a suit: Spades (S), Hearts (H), Diamonds (D) or Clubs (C)  and a value: 29, Jack (J), Queen (Q), King (K) and Ace (A).The cards are ranked (from lowest to highest) in the order given. One person is designated as the dealer, after each deal this role moves clockwise. To make the following description easier, assume that the four players are Amy, Bob, Carol and Dave and that they are sitting in that order clockwise around a table. Dave is the first dealer, Amy will deal next and so on.
Dave deals one card to each player face down, starting with Amy, and continues until all cards have been dealt (each player now has 13 cards). Amy now designates how many tricks she expects to take, a number between 0 and 13, (tricks will be explained later) and her personal trump suit, then Bob does likewise and so on. Dave as the last bidder must bid for a number of tricks such that the total number of tricks bid (by all four players) does not equal 13. After this has been done and recorded the play begins.
Amy then leads to the first trick, i.e. she lays a card face up on the table. Each player in clockwise then plays a card and the four cards constitute a trick. Each player must follow suit if possible, i.e. play a card of the same suit as that led. Players who cannot follow suit may play one of their personal trumps or just discard one of their other cards. The winner of the trick collects it and leads to the next trick. The winner is determined as follows. If a trick has not been trumped (the leader did not lead anyones personal trump suit and everyone either followed suit or discarded) then the highest card in the led suit wins. If the trick has been trumped, then the highest trump wins. If there are two or more trumps of equal value (remember that everyone has their own trump suit) then the first highest wins. For example, assume that at some stage Dave led a low diamond, that neither Amy or Bob have any diamonds left, and that Amys trump suit is Hearts and Bobs is Spades. If Amy plays HK and Dave plays SA, he would win. If Amy had played HA, she would have won, even if Dave had still played SA. When all 13 tricks have been played, players score the number of tricks they won. In addition, players who achieved their target (won the number of tricks they bid for) score an extra 10 points.
In order to simulate this game, we will make the following modifications. Bids will consist of only the desired trump suit, based on length. If two or more suits are equally long, value the suits by allocating 5 points to an Ace, 4 points to a King, 3 points to a queen, two points to a Jack and 1 point to anything else and bid the highest valued suit. If there is still a tie, bid the highest ranked suit in the order (from highest to lowest) S, H, D, C. At the end of a deal each player will merely score the number of tricks they won, without any bonuses.
When leading, lead the highest card in your trump suit if possible, otherwise lead the highest card in the highest ranking suit that is not someone elses trump suit. If this is not possible, lead the lowest ranked card in your hand (choosing the lowest ranked suit in case of a tie). When playing, always attempt to win the trick if you can, otherwise play as cheaply as possible. Thus you will play the highest card in the suit led, unless a higher card has already been played, in which case play your lowest card in that suit. If you cannot follow suit, play your highest trump if you can and if it could win. If you have no trumps, or your highest trump could not win the trick, then discard the lowest card in your hand. If you have two lowest cards, play the one from the lowest ranking suit (using the ranking given above).
Consider that the deck is (in order from the top of the deck to the bottom):
C8 HK D6 ST DT H5 S7 C9 DQ DK SA HA D2 S8 CT H8 SJ SQ S4 D8 D7 C3 SK H6 HT H4 HQ S2 C6 C2 H9 DJ C7 CK CQ H2 CA DA CJ D5 S3 D3 S6 D9 H3 D4 S5 C4 H7 C5 HJ S9Thus Dave will deal the C8 to Amy, HK to Bob, D6 to Carol and ST to himself and then continue. The resulting hands and bids are as follows:
Amy : C6 C7 C8 CA D2 D7 DT DQ H3 H7 HT S3 SJ bids C Bob : C2 C3 C5 CK D3 D4 DK DA H4 H5 HK S8 SQ bids D Carol: CT CJ CQ D6 H9 HJ HQ S4 S5 S6 S7 SK SA bids S Dave : C4 C9 D5 D8 D9 DJ H2 H6 H8 HA S2 S9 ST bids HAmy will lead to the first trick. In what follows, the leftmost card is the card led by the winner of the previous trick (indicated on the right of the previous line). The next three cards are the next three cards played. Note that the leftmost card is the card that was led, not necessarily the card played by Amy.
Trick 1: CA C2 CT C4 Amy Trick 2: C8 C3 CJ C9 Amy Trick 3: C7 C5 CQ HA Dave Trick 4: H8 H3 H4 H9 Dave Trick 5: H6 H7 H5 HJ Dave Trick 6: H2 HT HK HQ Dave Trick 7: S2 SJ SQ SA Carol Trick 8: SK S9 S3 S8 Carol Trick 9: S7 ST D2 DA Bob Trick 10: DK D6 D5 D7 Bob Trick 11: D4 S6 D8 DT Carol Trick 12: S5 D9 C6 CK Amy Trick 13: DQ D3 S4 DJ CarolThus at the end of the deal Amy has won 3 tricks, Bob 2 and Carol and Dave 4 each.
Write a program to simulate playing this game.
Input will consist of a series of decks (between 1 and 99, both numbers inclusive), each consisting of 4 lines of 13 cards without spaces as shown below and terminated by a line containing only ##.
For each deck in the input, output a line as shown below. After all decks have been processed output a summary line as shown.
Follow the spacing of the example exactly. The number of the deal is right justified in a field of width 5, the other numbers are right justified in fields of width 8.
C8HKD6STDTH5S7C9DQDKSAHAD2 S8CTH8SJSQS4D8D7C3SKH6HTH4 HQS2C6C2H9DJC7CKCQH2CADACJ D5S3D3S6D9H3D4S5C4H7C5HJS9 SAD3DTS4C9DAHJH6S8HACTD8H9 HTCQC5STHKHQS5D6C6D5H5H2H7 CKD7D4SJD2DQC3C8C4C2SQSKH3 DKD9H4CAH8S7CJS2S6C7DJS9S3 ##
Round 1: 3 2 4 4 Round 2: 4 3 3 3 7 5 7 7
______________________________________________________ 2012false
Four in a Line is a game similar to 3dimensional noughts and crosses. It consists of a horizontal table on which 16 pegs, each of which can hold 4 beads, are arranged in a 4 × 4 grid. Each player has a supply of either green or red beads which are placed on the pegs in turn, starting with red. Obviously, as each bead is placed on a peg, it slides down as far as it can  until it either hits another bead or the supporting table. The winner is the first to get 4 beads of their colour in a line (hence the name). The line can be in any plane and in any orientation, as long as the four beads are all of the same colour and form a straight line.
As with most games, the interesting part comes towards the end, when each player (colour) is attempting to build a line and block the opponents incipient lines. Write a program that will read in details of a game position and determine whether green (the next player) can be guaranteed to win the game within 5 plies. A ply is half a turn, in this situation placing one bead, thus 5 plies implies three moves by green and two by red.
Input consists of a number of games. Each game consists of 4 lines of characters, each line consisting of 4 blocks of 4 characters  R for red, G for green or # for empty  where each block represents the contents of a single peg with the left end representing the bottom. Thus the block GRR# represents a peg with a green bead on the bottom with two red beads above it. Note that the entire state of the game is always given, thus the starting state would consist of 64 # characters arranged in 16 blocks of 4. You can assume that the position is valid, i.e. that there will be exactly one more red bead than green beads, and that there will not be any holes in the description (the block GR#G, for instance). There will be one blank line after each game and input will be terminated by a line containing only a single #.
For each game description in the input, output a single line of the form "Green can win in N move(s)", where 1 ≤ N ≤ 3, and where N is the smallest such number, or "Green cannot win in 3 moves". Use the singular form when N = 1 and the plural form otherwise.
GGG# RR## R### R### #### #### #### #### #### #### #### #### #### #### #### #### RRR# RGG# RGG# #### #### #### #### #### #### #### #### #### #### #### #### #### #
Green can win in 1 move Green cannot win in 3 moves
______________________________________________________ 2013false
You are given a collection of sealed pizza boxes. The tops and bottoms of the boxes are covered internally with metal foil, but the edges are not. Inside, each box has been divided into r rows and c columns (both in the range 2 to 8 inclusive), after the manner of a chess board. Each of the thusformed internal squares is either empty or contains a single widget. Widgets absorb beta radiation slightly, so by placing a beta emitter on one side of a box and a receiver on the other side you can tell how many widgets there are in the line of sight between emitter and receiver, but not where they are. By appropriate placement of the emitters and receivers we can determine the occupancies along various lines, i.e. how many widgets there are in each row (r numbers), column (c numbers), down diagonal (r+c1 numbers), and up diagonal (r+c1 numbers)
For example, the following 8 by 8 configuration will produce the numbers shown.
The input to the program is a sequence of problems, each consisting of five lines of integers. The first line of each problem contains r and c (2 ≤ r ≤ 10, 2 ≤ c ≤ 10), line 2 contains r numbers giving the row occupancies, line 3 contains c numbers giving the column occupancies, line 4 contains r+c1 numbers giving the down diagonal occupancies and line 5 contains r+c1 numbers giving the up diagonal occupancies. A line of two zeroes (0 0) for r and c terminates the input.
The output of the program is a sequence of pictures, one per input problem except for the terminal one. The first line of the output contains the words "Pizza box" followed by a single space and the number of the problem (a running number starting at 1). The next r lines each contain c characters  either a # for a full square or  for an empty square. Leave a blank line between problems.
4 3 3 1 1 2 2 1 4 1 2 2 1 0 1 1 1 1 2 1 1 8 8 0 2 2 2 3 2 3 0 0 2 2 2 3 2 3 0 0 0 0 0 3 2 0 4 0 2 3 0 0 0 0 0 0 0 0 3 2 0 2 1 2 3 0 1 0 0 0 0
Pizza box 1 ### # # ## Pizza box 2  ## ## ## ### ## ### 
______________________________________________________ 2014false
Lauries little brother Joey has been playing Find the Cookie with her. However, after the 32,767^{th} time, Laurie is tired of it. She wants to write a program to keep the boy occupied. Write a program to simulate a game of Find the Cookie. The game takes place in a long narrow hall, so Joey can only move forward and backward, not right or left. At the beginning of each game, a cookie is placed in the hall (not at the center of the hall) and Joey starts at the center of the hall. Joey attempts to find the cookie. He does this by moving to another point in the hall, whereupon the computer tells him whether he is "warmer" (he has moved closer to the cookie than his last position), "colder" (he has moved farther away from the cookie than his last position), "same" (he has not moved closer or farther away from the cookie), or he has reached the cookie. Joey continues until he exactly reaches the location of the cookie, which always happens within 20 moves.
5 10 11 12 3 4 5 3 10 10 7 3 12 5 3 1 4 6 7 8 9 12 5280 10
Moving from 0 to 10: same. Moving from 10 to 11: colder. Moving from 11 to 12: colder. Moving from 12 to 3: warmer. Moving from 3 to 4: warmer. Moving from 4 to 5: found it! Moving from 0 to 10: colder. Moving from 10 to 10: same. Moving from 10 to 7: warmer. Moving from 7 to 3: found it! Moving from 0 to 5: warmer. Moving from 5 to 3: colder. Moving from 3 to 1: warmer. Moving from 1 to 4: warmer. Moving from 4 to 6: warmer. Moving from 6 to 7: warmer. Moving from 7 to 8: warmer. Moving from 8 to 9: warmer Moving from 9 to 12: found it!
______________________________________________________ 2015false
Bingo is a game played on a 5 by 5 board called a card. There are many variations, but Bob's Bingo uses the following rules:
Each card will have the 25 positive integers, where each value is less than or equal to 75. No value will appear in more than one position on a card. During the game, numbers are selected and if they are on a card, they are covered. To be a winner, all the numbers on a card in a given pattern must be covered. The pattern can change from game to game. Some sample patterns (marked by the Xs) include:
Two different cards may both be winners for a given pattern. Consider the cards and pattern below:
Both of these cards are winners when the numbers 1, 2, 7, 8, 13, 14, 19, 20, and 25 are selected. These are considered to be equivalent cards.
Bob's Bingo players get mad when they have two equivalent cards (since it reduces their chance to win) or when one of their cards is equivalent to a card of another player (since they have to share the prize). Bob wants you to write a program to go through his stack of cards and identify the equivalent cards.
The input data file contains a collection of one or more independent datasets where each represents the cards for one game.
Each dataset begins with the winning pattern for the game. This will be entered as 5 lines, with 5 characters (either 'X' or '_') on each line. Each line will be one row of the pattern with an 'X' representing a position that is part of the pattern and an '_' representing a position that is not part of the pattern. Each pattern will have at least one 'X'.
After the pattern will be a line containing a single integer n, with 0 ≤ n ≤ 100. Then there will be n cards, where each card is represented by 5 lines of 5 integers each, with at least one space between the integers on a line. Each line of input represents one row of the card.
The end of input will be marked by a dataset with 0 cards to check. This dataset should not be processed.
For each dataset, first output the number of the dataset (starting at 1). Then, for each card that is equivalent to a previous card, output a line stating "Card k is equivalent to card m" where k is the number of the current card in the set and m is the earlier card that is equivalent to card k (where card numbering starts at 1). If the current card is equivalent to more than one other card in the set, print the lowest numbered one. If there is no earlier card equivalent to the current card, you should not print any output for the card.
Have one blank line between outputs for consecutive datasets.
X____ XX___ _XX__ __XX_ ___XX 4 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 7 18 60 64 65 14 19 4 21 50 40 20 25 52 5 49 75 13 2 43 74 63 9 8 1 1 3 4 5 6 2 7 31 32 33 34 13 8 35 36 37 38 19 14 39 40 41 42 20 25 _XXX_ X_X_X XXXXX X_X_X _XXX_ 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 X____ XX___ _XX__ __XX_ ___XX 0
Game 1 Card 3 is equivalent to card 1 Card 4 is equivalent to card 1 Game 2 Card 2 is equivalent to card 1
______________________________________________________ 2016false
Dozens of charity WWW sites have appeared recently. These sites donate advertising payments they receive to charitable organizations. But advertisers don't want to pay for people who come to the WWW site dozens of time a day, so require a list of unique visitors to the site. Some sites, such as The Hunger Site (thehungersite.com), the original "Click for Charity" site, allow only one donation per address per day. Others, such as the Meals On Wheels site (givemeals.com), allow donations as frequently as every 6 hours.
You are to write a program to take a list of visits for a month and list the visitors to the site and the number of visits, both valid and invalid, they made in that month.
The input data file contains zero or more records of visitors to a charity WWW site, where each record appears on single line. Each visit will be in the following format:
dd:hh:mm:ss:address
where:
dd is an integer that represents the day of the visit, with 01 ≤ dd ≤ 32 hh is an integer that represents the hour of the visit, with 00 ≤ hh ≤ 23 mm is an integer that represents the minute of the visit, with 00 ≤ mm ≤ 59 ss is an integer that represents the second of the visit, with 00 ≤ ss ≤ 59 address is a string that represents the email address of the visitor. The address will consist of the upper and lower case letters, digits, periods ('.'), and the at sign ('@') only. It will have exactly one '@' in it (that will not be the first character) and at least one period after the '@'. The '@' and '.' will not appear next to each other. An address will not end with a '.'. There will be at most 65 characters in the address. Case is not significant in addresses, so a@b.c and A@B.C should be considered to be the same address.
The visits will be arranged in time order, from earliest to latest. While there may be two or more visits at a given time, there will not be two visits for the same address at the same time.
There will be at most 1000 unique addresses in the input file.
The end of input will be indicated by an entry for day 32. This line should not be processed.
Output the number of valid and invalid visits for each address in the file. A visit is valid if it is the first visit in the file for the address or if it is 6 hours or more since the most recent previous valid visit for that address. A visit is invalid if it is not valid (that is, if it is less than 6 hours since the last valid visit for that email address in the file).
Output should be grouped by toplevel domain, and within a toplevel domain by the secondlevel domain. The toplevel domain of the address is the character or characters after the last period in the address. The secondlevel domain is the collection of letters and digits immediately before the last period. For example, the address programmer@acm.cs.gcsu.edu has the toplevel domain edu and the secondlevel domain gcsu . Toplevel domains should be alphabetized, then the secondlevel domains alphabetized under them. For each secondlevel domain, all the donors in that domain should be listed in ASCII order of address, followed by the number of valid donations and invalid donations. There should be one blank line between secondlevel domains and two blank lines between toplevel domains. Use the format in the sample output.
All email addresses in the output should be in lower case.
01:00:24:18:joe@gcsu.edu 01:00:24:18:jane3@cobra.cs.mercer.edu 01:01:00:29:joe@gcsu.edu 01:07:00:29:JOE@GCSU.EDU 01:08:30:15:JANE3@COBRA.CS.MERCER.EDU 01:12:02:19:THOMAS@USA.EDU 02:08:30:15:jane@cobra.cs.mercer.edu 04:07:20:00:bob@ist.ucf.EDU 04:08:18:39:mickey@disney.com 04:13:19:59:bob@ist.ucf.edu 04:18:20:19:thomas@usa.EDU 05:19:19:45:rudy@survivor.cbs.tv 06:00:18:24:jane3@cobra.cs.mercer.edu 06:01:19:45:Rudy@Survivor.CBS.TV 10:00:24:18:joe@gcsu.edu 32:01:02:03:last.name@the.list
TOPLEVEL DOMAIN = com Second level domain = disney mickey@disney.com 1 0 TOPLEVEL DOMAIN = edu Second level domain = gcsu joe@gcsu.edu 3 1 Second level domain = mercer jane3@cobra.cs.mercer.edu 3 0 jane@cobra.cs.mercer.edu 1 0 Second level domain = ucf bob@ist.ucf.edu 1 1 Second level domain = usa thomas@usa.edu 2 0 TOPLEVEL DOMAIN = tv Second level domain = cbs rudy@survivor.cbs.tv 2 0
______________________________________________________ 2017false
The Olympic committee has hired American Code Masters (ACM) to verify the IDs issued to all the athletes, reserves, judges, staff, and the press. Each badge has a barcode written on it in base5, encoding the ID number. The system of ID numbers uses a checkdigit scheme to detect errors and reduce forgeries. You are to write a program to help ACM detect invalid ID numbers.
The devices that security uses to read the barcodes produce strings of the letters V,W,X,Y,Z. Each letter represents a base5 digit: V represents 4, W represents 3, X represents 2, Y represents 1, and Z represents 0. So, WXZ=320 (base5), which is 85 (base10). The base5 number is first converted to a base10 number. Any number with more than 8 (base10) digits is considered invalid. Numbers with less than 8 digits are padded on the left with zeroes. IDs are allocated based on the most significant digit (in base10):
0, 1 athletes;
2, 3 reserves,
4, 5 judges;
6, 7 staff; and
8, 9 press.
Consider the ID number d_{7} d_{6} ... d_{1} d_{0} expressed in base10, where d_{i} (0≤i≤7) is a single digit of the ID number. For this ID to be valid the following checksum value must be 0:
F(0,d_{0}) x F(1,d_{1}) x F(2,d_{2}) x ... x F(6,d_{6}) x F(7,d_{7})We will define the function F(i,j) and the operator x next. The function F is defined as:
That is, G(0)=1, G(1)=5, etc.
The function i x j is based on dihedral groups and has the nice property that transposing digits in the ID creates a checksum error. It is defined as follows:
The first line of the input contains an integer n³1. Each of the next n lines contains a single scanned barcode representing a potential ID number. Each scanned barcode will consist only of the characters 'V', 'W', 'X', 'Y', and 'Z' and will be at least 1 and at most 12 letters long.
You should output the ID number as read, its corresponding base10 number, and a message telling either that the ID is invalid or, if it is valid, the type of participant that the ID belongs to. Use the wording and format in the sample output below.
6 WYYXWVZXX YWYWYYXWVZYY YWYWYYXWVZYX YYZWYYXWVZYX YXXWYYXWVZXW XYXWYYXWXYY
WYYXWVZXX/01274262 is valid athlete id number YWYWYYXWVZYY/81352381 is valid press id number YWYWYYXWVZYX/81352382 is invalid id number YYZWYYXWVZYX/59868007 is valid judge id number YXXWYYXWVZXW/73539888 is valid staff id number XYXWYYXWXYY/22520431 is valid reserve id number
______________________________________________________ 2018false
The coaches for the US Olympic Track Team, Pierre A. Noid and Ada Noid, fear that their 16yearold, 7 2 javelin thrower, Moven van Driver, has not been given a "fair go" by the Olympic referees. They have purchased two distance measuring devices (DMD) to help them check on the accuracy of the measurements made by the referees. There are several elimination rounds for which each coach positions him/herself in either coaches area (which includes the boundaries), such that the two coaches are on opposite sides of the throwing zone. At the beginning of each round the coaches measure their separation from each other and the distance of each from the launching point. During a round the coaches do not move. For each throw in each round they record their distances from the landing point, and calculate the distance that should have been awarded to Moven. You may assume that the javelin will always land somewhere in the landing area (which includes its boundary).
There will be several groups of input data, each representing a round. The first line of each group will have an integer and three real numbers, n, x, y, and z separated by white space. The first number n is the number of throws in the current round, such that 0 ≤ n ≤ 5. The other distance limits are 10 ≤ x ≤ 100, 10 ≤ y ≤ 100, and 5 ≤ z ≤ 100. The next n lines will have pairs of real numbers, representing measurements a and c, such that 1 ≤ a ≤ 100, and 0 ≤ c ≤ 100. The input data is terminated by a value of n=0, followed by three zeros, and this data is not processed.
The output should be labeled by the number of the round, and followed by the distance of each throw for that round (each on a separate line). Formatting should be as in the sample output.
3 50.00 50.00 75.00 50.00 50.00 60.00 40.00 30.00 75.00 2 30.00 60.00 87.50 55.55 66.66 33.33 88.88 0 0 0 0
Round 1 1. 66.14 2. 66.30 3. 69.96 Round 2 1. 52.77 2. 48.81
______________________________________________________ 2019false
Dolores's house has an unusual semicircular driveway that can accommodate 26 cars in a single file, with exits at the front and the back. This is nice because when she hosts a party because everyone can park in the driveway. However, it causes complications when a guest wants to leave, because other guests with cars blocking that person must move their cars temporarily. Her guests take this in stride, and make a game out of the nuisance. When someone leaves, those cars that must move return to the driveway in reverse order. Since there are two ways for the leaving car to exit (through the front or rear exit), the cars on the shorter path to an exit must move (and return in reverse order). If the car that wants to leave is exactly in the middle, the front cars (on the left) must move.
For example, suppose the initial driveway configuration is represented as ABCDEFG. Suppose further that the owner of car E decides to leave. Then the owners of cars F and G must move (since theyre on the shorter path to an exit) to make room for E to leave, and then return to the driveway in reverse order. The new driveway configuration will be ABCDGF. Suppose now C wants to leave. Here, A and B have to move (since theyre on the shorter path to an exit) , with the resulting configuration BADGF. Lets say that now D wants to leave. In this case, B and A must move (since both exit paths are of equal length, and A and B are on the path to the front exit). The resulting configuration is ABGF.
Write a program to simulate this party game.
Each data set begins with a line containing only a string of uppercase letters, representing the initial order of cars in the driveway as described above. The string will contain at least one letter, and no letter is duplicated. The next line contains an integer n ≥ 0. The next n lines each contain only a single uppercase letter, indicating the next car to leave the party; this letter is guaranteed to represent one of the remaining cars at the party. Your program should stop processing data sets when it reaches an initial driveway order of STOP.
Begin the output for each data set by indicating the data set number and the initial order of cars in the driveway. As each car leaves, output the new car order. Follow the output format indicated in the Sample Output. Leave a blank line between the output for different data sets.
ABCDEFG 3 E C D HIWORLD 1 H STOP
Dataset #1: The initial order is ABCDEFG. After E leaves, the order is ABCDGF. After C leaves, the order is BADGF. After D leaves, the order is ABGF. Dataset #2: The initial order is HIWORLD. After H leaves, the order is IWORLD.
______________________________________________________ 2020false
The judges at the programming contest have been watching the Olympics, and are considering using style judging at next years contest. Particularly, they like the model used in the diving competition where each problem is given a degree of difficulty and then six judges will give it a score on a scale from 0.0 to 10.0. The high and low score will be discarded, the other four scores added up, and then the sum is multiplied by the degree of difficulty. The team with the highest total score for all their problems is declared the winner.
Your job for this problem is to write a program that will read in the number of teams and problems, each problems degree of difficulty, and the problems that are submitted by each team at an actual competition along with each of the six judges scores for those problems. The program will then print a summary showing each teams score on each of the problems along with the winning team number and their score. A team is allowed to submit a problem more than once without penalty, but the judges scores for the most recent submission are the ones that are used. In case more than one team has an overall score within three hundredths of a point of the high score, your program should indicate there is a tie and list the teams with multiple high scores.
The input file will consist of data sets for one or more contests. Each data set will begin with a single integer 0 < n ≤ 9, representing the total number of teams competing in the contest. This will be followed by a line that begins with an integer 0 < p ≤ 9 indicating the number of problems at the competition, and then p numbers representing the judges difficulty ratings for each of the problems. Each of the difficulty ratings is a nonnegative fixed point value with exactly one digit after the decimal point. All judges scores are fixed point numbers in the range from 0.0 to 10.0 with one digit after the decimal point. The next lines contain a teams submission and the six judges scores for that submission in the following format :
TeamNumber ProblemNumber Score_{1} Score_{2} Score_{3} Score_{4} Score_{5} Score_{6}
The end of input for a given contest is indicated by the string "TIME'S UP" starting in column 1. A line of "END" starting in column 1 indicates end of input and should not be processed.
The first line of output for each contest should be the number of the contest, where contest numbering starts with 1. The program should then print a summary showing the problem numbers, followed by a blank line, and then the team number of each team starting with the first team along with their total scores for each of the respective problems in a tabular format as shown below. All team and problem numbers are numbered with positive integers starting at 1 and continuing with each consecutive integer thereafter. The score for each team should be rounded to one digit to the right of the decimal point. This should be followed by a blank line, the team number(s) with the most points, and the overall winning point total.
Prob_{1} Prob_{2} Prob_{3} ... Prob_{j} Team_{1} Score_{1} Score_{2} Score_{3} ... Score_{j} Team_{2} Score_{1} Score_{2} Score_{3} ... Score_{j} Team_{3} Score_{1} Score_{2} Score_{3} ... Score_{j} . . . . . . Team_{i} Score_{1} Score_{2} Score_{3} ... Score_{j} Team x wins with xxx.x points
In case of a tie between two teams, the final line should be written in the following format:
Tie for first with xxx.x points among these teams : x x
If the tie is between more than two teams, simply continue listing your team numbers with a single space between each.
Have two blank lines after each contest.
4 3 2.1 1.9 1.8 2 2 6.0 2.1 6.5 7.0 8.0 7.5 1 2 1.9 5.0 6.5 7.0 7.0 5.5 3 3 1.8 5.5 8.5 7.0 6.0 6.0 4 3 2.3 7.0 7.0 7.0 7.0 7.0 2 3 2.3 7.0 7.0 7.0 7.0 7.0 2 1 1.9 5.0 6.5 7.0 7.0 5.5 1 1 1.9 5.0 6.5 7.0 7.0 5.5 3 1 1.9 5.0 6.5 7.0 7.0 5.5 2 3 8.0 7.5 7.5 8.0 7.5 7.0 1 3 6.9 5.5 6.5 7.5 7.0 8.5 4 2 5.5 7.5 7.0 7.0 8.0 7.5 TIME'S UP END
Contest 1: 1 2 3 1 50.4 45.6 50.2 2 50.4 51.3 54.9 3 50.4 0.0 44.1 4 0.0 55.1 50.4 Team 2 wins with 156.6 points
______________________________________________________ 2021false
Starting with an initial colorless background, we will paint a sequence of potentially overlapping, horizontallyaligned rectangles of various colors. The problem is to determine the exposed area of a given color.
The input data file contains a collection of independent datasets.
The first line of each dataset contains two numbers. The first number is an integer 0 ≤ n ≤ 1000 specifying the number of rectangles that follow. The second number is a positive integer 0 < c < 8, representing the color whose exposed area we want to determine.
Each of the next n lines of the dataset contains information about a rectangle, and the lines are given in order of the painting sequence. The first number on the line is an integer 0 < c' < 8, representing the rectangles color. The next two integer values on the line are respectively the x and ycoordinates of any corner of the rectangle. The last two integer values are respectively the x and ycoordinates of the diagonally opposite corner of the rectangle. All coordinates lie in the range from 100 to +100 inclusively.
The end of input will be indicated by a dataset with n = 0. This dataset should not be processed.
For each dataset, the output of your program will be a single line containing the string "The area of color x in dataset y is: " followed by a single integer representing the area (in square units) of the exposed color specified in the dataset.
4 2 2 6 0 0 4 4 1 4 3 1 2 3 3 8 7 5 2 2 4 6 1 5 7 0 0 1 1 2 3 3 0 0 2 2 4 0 0 1 1 0 1
The area of color 2 in dataset 1 is: 31 The area of color 5 in dataset 2 is: 0 The area of color 3 in dataset 3 is: 3
______________________________________________________ 2022false
Air transportability is concerned with the packing of cargo on aircraft. In order to ensure safe takeoffs and landings, cargo must be packed according to rigorous rules, which can vary from airplane to airplane. Rules for packing aircraft are:
All aircraft will have weight limits. They cannot hold more than their weight limit, and for the sake of efficiency, no plane may carry less than 50% of its weight limit. Cargo items are rectangular and have uniform weight distribution. Two adjacent items must be at least 1 foot apart to allow for tie downs. All aircraft will have a rectangular area for cargo, the cargo hold. No cargo can be placed within one foot of the edge of the cargo hold to allow space to tie it down. At least 60% of the cargo weight must be put in the front half of the cargo hold. The weight on the left side of the center line must be no more than 5% more or less than the weight on the right hand side of the center line. If a piece of cargo can be moved toward the rear of the plane and still meet the other constraints, then it should be moved toward the rear of the plane because all loading and unloading takes place at the rear of the plane. To allow for speedy loading and unloading, no plane may hold more than 10 items.
You are to write a program to help allocate cargo to aircraft efficiently.
The input will consist of one or more input sets. The first line of each input set will be an integer 0 ≤ p ≤ 20 which represents the number of planes to be loaded. There will then be p sets of plane information. Each set of plane information has two lines. The first has a string of 1 to 25 characters representing the name of the aircraft. No two different aircraft in an input set will have the same name. The second line will have four integers, 0 < x ≤ 100, 0 < y ≤ 30, 0 < w ≤ 100000, 0 < c ≤ 20000 where:
x represents the length of the cargo hold (from the front of the plane to the rear of the plane) in feet, y represents the width of the plane (from left to right) in feet, w represents the weight limit of the plane in pounds, c represents the cost of the plane in dollars.
After the plane information will be the information about the cargo to be loaded. The first line will have a single integer 0 < n ≤ 200, representing the number of pieces of cargo to be loaded. There will then be n sets of cargo item information. Each line of cargo information will consist of 4 integers 0 < i ≤ 1000, 0 < len ≤ 20, 0 < wid ≤ 20, 0 < wt ≤ 10000, where:
i is a unique value that identifies the cargo item and gives its relative priority (where the higher the value, the more important the item) len is the length of the item in feet wid is the width of the item in feet wt is the weight of the item in pounds
Items cannot be turned when they are loaded on the aircraft, so the lengthwise side of the cargo item must be loaded lengthwise along the aircraft. The end of input will be a set with p = 0. This set should not be processed.
If it is possible to load all of the cargo meeting the constraints, you should load the cargo using the most inexpensive collection of planes, given the constraints above. If all of the cargo cannot be loaded, you should load as many items as possible without regard for cost. If two configurations load the same number of items, select the configuration with the highest total priority. If two configurations have the same number of items loaded and the same priority and meet all of the above constraints, print either one.
The first line of output for each input set should include the number of the set (starting with 1) and the total cost of the planes used to transport the set. Then, for each plane used, give the name of the plane on a line by itself followed by one line for each of the cargo items on the plane (in ascending numerical order of priority), giving the cargo item number, and the distance of its leftmost front corner from the front of the cargo hold and the left edge of the cargo hold (because of the position of tie downs, these must be integer values). Finally, on the last line of the output, if there are pieces of cargo that cannot be loaded, list them, in numerical order of priority.
Have a blank line between output for consecutive input sets and use the format in the sample output.
2 C5A, first 100 30 100000 20000 Cessna 10 5 1000 200 5 400 20 20 56000 300 20 20 4000 80 20 10 30000 900 20 10 10000 5 5 3 400 0
Plane loading 1: C5A, first 80 loaded at 79 back, 1 from left 300 loaded at 30 back, 5 from left 400 loaded at 9 back, 5 from left 900 loaded at 79 back, 19 from left Unloaded: 5
______________________________________________________ 2023false
A television game show host begins each new game by selecting a player, as follows. The host asks candidate players to order four items. The first candidate to order the items correctly wins. If there is a tie for the fastest time, or if no one correctly answers, the host poses a new question. The producers air only questions that select a player. They are unhappy with their current player selection software and are seeking a replacement.
The candidates have at most 30 seconds to answer the question. During this time, they press buttons A, B, C, or D, indicating how to order the items. Pressing a special rub out button marked X erases the last selection (this has no effect if there are no characters to rub out). For example, after pressing BXXACXDXBDC, the candidate has selected the answer ABDC. Each candidates selection is sent to the software along with a timestamp (from 0 to 300, in tenths of a second) and a number identifying the candidate. A candidate cannot make simultaneous selections (i.e., with the same timestamp), but two different candidates might make selections at the same time. Although the software receives the messages in time sequence for a particular candidate, messages from two different candidates may arrive out of time sequence. For example, the software might receive the following sequence:
The input contains several player selection rounds. Each round begins with a line containing two integers m and n separated by whitespace, where 2 £ m £ 10 is the number of candidates and n is the number of messages. The next line contains only the letters A, B, C, and D, in the correct order for that round; each letter appears exactly once and in upper case. The next n lines contain the messages in the following format:
candidate timestamp selection
where candidate is an integer between 1 and m inclusive that identifies the candidate sending the message, timestamp is an integer between 0 and 300 inclusive representing the time in tenths of a second, and selection is either A, B, C, D, or X (in upper case) as explained above. Your program must stop processing input when it encounters a data set in which n is 0.
Begin the output of each player selection round by summarizing the results. List the candidates in order of candidate number and state whether the candidate was correct or incorrect. If the candidate was correct, indicate the time at which the candidate completed data entry. If a player is selected, indicate which player. If no player is selected, indicate that this question should not be aired and a new question is needed. Leave a blank line between the output for different player selection rounds. Follow the format shown in the Sample Output.
2 10 BDAC 1 20 B 2 10 B 1 50 C 2 40 D 1 70 X 1 110 D 1 120 A 2 100 A 2 150 C 1 170 C 2 8 ABCD 1 20 A 1 25 B 1 78 D 2 15 C 2 59 D 2 105 A 2 189 B 1 187 C 2 0
Round #1: 2 candidates Candidate 1: Correct in 17.0 seconds Candidate 2: Correct in 15.0 seconds Candidate 2 is selected as the player for this round. Round #2: 2 candidates Candidate 1: Incorrect Candidate 2: Incorrect Dont air this one...we need a new question.
______________________________________________________ 2024false
A convoy of vehicles has lined up on a single lane and oneway street in front of a single lane and oneway bridge over a river. Note that since the street is single lane, no vehicle can overtake any other. The bridge can sustain a given maximum load. To control the traffic on the bridge, operators are stationed on both ends of the bridge. The convoy of vehicles is to be divided into groups, such that all the vehicles in any group can cross the bridge together. When a group reaches the other side, the operator on that side of the bridge uses a telephone to inform the operator on this side that the next group can start its journey over the bridge. The weight of each vehicle is known. The sum of the weights of the vehicles in any group cannot exceed the maximum load sustainable by the bridge. Associated with each vehicle is the maximum speed with which it can travel over the bridge. The time taken by a group of vehicles is calculated as the time taken by the slowest vehicle in the group to cross the bridge. The problem is to find the minimum amount of time in which the entire convoy can cross the bridge.
The file has several inputs. The first line of input contains three positive integers (separated by blanks): the first one represents the maximum load that the bridge can sustain (in tones); the second one represents the length of the bridge (in km); and the third one is the number of vehicles n in the convoy. Each of the next n lines of input contains a pair of positive integers, w and s (separated by blanks), where w is the weight of the vehicle (in tones) and s is the maximum speed (in km/h) with which this vehicle can travel over the bridge. The weights and speeds of the vehicles are specified in the same order as the order in which the vehicles are queued up. You can assume that n < 1000. The file ends when n = 0.
The output of each dataset should be a single real number on a line by itself specifying the minimum time in minutes in which the convoy can cross the bridge. Print the number with exactly one decimal digit.
100 5 10 40 25 50 20 50 20 70 10 12 50 9 70 49 30 38 25 27 50 19 70 0 0 0
78.0
______________________________________________________ 2025false
Assume that you work for the Digital Processing Lab. They ask you to write a program with an input binary matrix A, which contains the pattern to search on other binary matrix B. The input file include the size and elements for both A and B. The recognition process consists in scanning row by row (horizontal scanning) the matrix B, when a pattern is located on B you must mark this pattern. To mark a located pattern change 1 to 2 and 0 to * on B. The output file of your program will be the matrix B with the located patterns marked.
The first line of the input contains the number of test. For each test, the first line contains the size of A, next lines contains the matrix A row by row, next line contains the size of B and next lines contains the matrix B row by row. Each test will be separated by exactly one empty line.
For every test, the output is the matrix B with the located patterns marked. Output one empty line between test.
4 2 2 1 0 1 1 5 5 1 1 0 0 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 1 5 5 1 1 0 0 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 5 5 1 1 0 0 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 1 2 6 1 0 0 1 0 1 1 1 1 0 1 0 5 5 1 1 0 0 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 1
1 2 * 0 0 0 2 2 0 0 2 * 0 1 0 2 2 1 2 * 0 0 1 2 2 2 2 0 0 0 0 2 2 0 0 2 0 0 2 0 2 2 2 2 0 0 0 2 2 2 1 1 * * * * 1 1 * * 1 * * 1 * 1 1 1 1 * * * 1 1 1 1 1 0 0 0 0 1 1 0 0 1 0 0 1 0 1 1 1 1 0 0 0 1 1 1
______________________________________________________ 2026false
Consider a set D={1,2,3,...,n}.
A permutation of the elements of D is an ordered array a = a_{1}a_{2}a_{3}...a_{n} of all the distinct elements of D.
The number of permutations of D is n!.
Sample:
Let D={1,2,3}, then #Permutations = 3! = 6, and Permutations = { 123, 132, 213,231, 312,321 }
Lexicographical order
Let a = a_{1}a_{2}a_{3}...a_{n} and b = b_{1}b_{2}b_{3}...b_{n} permutations of D, then a < b if only if for some m with 0 < m < n and a_{1} = b_{1}, a_{2} = b_{2}, a_{3} = b_{3}, ..., a_{m1} = b_{m1} and a_{m} < b_{m}.
Check that the sample above is in lexicographical order.
Generating Permutations
If the permutation b is the lexicographical successor of the permutation a, then we can get b from a using the next procedure:
1. Look for the greater m that a_{m} < a_{m+1}.
2. Make b_{1} = a_{1}, b_{2} = a_{2}, ..., b_{m1} = a_{m1}.
3. Make b_{m} equal to the minor value of a_{m+1}, a_{m+2}, ..., a_{n}, that is greater than a_{m}.
4. Make b_{m+1} < b_{m+2} < ...< b_{n}.
Make a program that accept in an input file the number of elements n (0 < n < 10) of D and generate in an output file all the permutations of D lexicographically ordered.
The input is the number of elements n (0 < n < 10) of the set D. There might be several runs in the input file. Your program should stop when n = 0.
The output will be the name of the run, the value of n, follow by the list of all the permutations of D lexicographically ordered. There should be a blank line between runs.
1 2 4 0
Run 1 n=1 1 Run 2 n=2 1 2 2 1 Run 3 n=4 1 2 3 4 1 2 4 3 1 3 2 4 1 3 4 2 1 4 2 3 1 4 3 2 2 1 3 4 2 1 4 3 2 3 1 4 2 3 4 1 2 4 1 3 2 4 3 1 3 1 2 4 3 1 4 2 3 2 1 4 3 2 4 1 3 4 1 2 3 4 2 1 4 1 2 3 4 1 3 2 4 2 1 3 4 2 3 1 4 3 1 2 4 3 2 1
______________________________________________________ 2027false
An aerial photograph represents a square portion of an islands vegetation as a positive integer matrix. Each number in the matrix corresponds to a square subsection of the total area and contains relevant information about the plants that inhabit that particular place. For example, plant species that are unique to the island are represented with prime numbers, while species that can be found elsewhere are represented with nonprime numbers. The Botanical Institute of the island wants to divide the area into regions that have unique vegetation, and those that do not. To accomplish this task, the Institute has requested you to analyze the supplied information and determine the number of different regions that exist and their sizes. Two subsections belong to the same region if they lie contiguously on the same row or column, and if they both are either prime or nonprime.
The input to this problem is given out as sets of square areas. Each set contains the size of the area to analyze in a line by itself and is followed by the corresponding integer matrix, with each row occupying one line. A nonpositive integer for the area size indicates that no more sets should be analyzed. The size of the matrix will not exceed 100 units per side and integers will not be larger than 100,000,000.
For each set write the set number on the first line. On the next line output the number of regions of unique vegetation followed by the number of cells sorted in increasing order, that corresponds to each region. On the third line write the number of regions with nonunique vegetation. Output should be formatted as in the sample and an empty line must separate output from different sets.
3 2 4 9 17 6 37 29 8 11 4 2 3 12 15 5 7 21 33 4 6 11 17 8 9 13 29 1
Area 1: 2 unique vegetation regions: 2 3 1 nonunique vegetation regions Area 2: 2 unique vegetation regions: 4 4 2 nonunique vegetation regions
______________________________________________________ 2028false
In this problem you will be given a map of a rectangular maze with square blocks. From each block you can move in four directions (N, E, W, S) and you lose some energy for every walk from one block to an adjacent one. Some blocks of the maze are really blocked  that is you cannot move to those blocks. Some other blocks contain some treasures that you will have to collect. Each treasure has a particular pickup cost and carrying cost associated with it. The pickup cost is the energy required to pick up the treasure from the floor and the carrying cost is the energy required to carry the treasure from one block to an adjacent one. Now given a starting and ending location in the maze you will have to plan a single walk from the starting location to collect and carry all the treasures to the ending location at the expense of minimum energy.
The first line of the input contains two integers R and C (each < 21) describing the dimensions of the maze. Then follows R lines of C characters each representing the map of the maze. Each character corresponds to a square block and represents its property ('.' : an empty block, '#' : a blocked block, '*' : a block containing a treasure, 'S' : the starting block, 'T' : the ending block). The next line contains an integer representing the energy required in calories for a walk from a block to an adjacent one.
The next line contains pairs of integers (P_{i}, C_{i}) representing the pickup and carrying cost in calories for the treasures given in the map from top to bottom and for the same row from left to right. There will be at most 10 treasures in the maze. The input may contain several test cases and ends with two zeros for R and C.
For each test case first output the hunt number. In the next line print the minimum energy required for the hunt. The third line will contain the description of the hunt as a sequence of characters containing 'N', 'E', 'W', 'S' and 'P'. 'N', 'E', 'W' and 'S' represent a walk to the north, east, west and south respectively and 'P' means that the treasure is picked up from the current location. If the hunt is impossible just output the sentence 'The hunt is impossible.' in a line by itself. Each test case must be followed by a blank line.
5 8 #......T ..#*..#. ..###### ...*...# ####S.#* 5 10 50 50 100 30 80 10 10 #........* ..#*..#... ..######.. .......#.. ####S..##. .*.#...#.. .......#.. .##.#....# .*.....#.# ....*..#.T 10 100 400 20 50 150 250 30 70 4 5 0 0
Hunt #1 The hunt is impossible. Hunt #2 Minimum energy required = 17539 cal NWWWNNNEESPNWWSSSEEESSSWSSESPWWWNPW NNENPESEEESEEENENNNNNNPSSSSSWSSSSE
______________________________________________________ 2029false
Mr. Richards, an enthusiastic mathematician, is spending his holiday in Shanghai. He is so crazy about his study that he may associate anything with mathematical problems. According to his schedule, he should visit the Museum today. But after getting up, he was in a daze in the hotel, thinking deeply about a coloration problem. Yesterday, when he took a walk in the nightfall, the slabs of stone paved on the piazza fascinated him. He has associated those stones with a combinatorial problem.
The shape of those slabs of stone is equilateral triangle whose side length is 1 meter. But if Mr. Richards arranges 4 slabs of stone, as Fig.1 below shows, those stones may form a larger equilateral triangle whose side length is 2 meters. He designates those stones with the numbers 1 to 4 first, then he tries to use three different colors  blue, green and red  to color those stones. In such a triangle, the contiguous stones are required not to be painted with the same color. He asks himself to find out the number of the coloration methods. Since he is a learned person in combinatorial theory, it's not a difficult problem for him. Soon he works out the answer, 24. You know, because of the marks on those stones, they should not be regarded as the same ones.
Arranging for more slabs of stone to form a larger triangle, and using more colors, the coloration problem will be much more complex. For example, arranging 9 slabs of stone, as Fig.2 below shows, Mr. Richards has to form a triangle whose side length is 3 meters. Using 5 colors to paint on those stones, the answer will be an enormous number. Without a computer, he could not tell the result exactly, although he knows clearly how to account the coloration methods. So you are required to write a program to tell him the exact answer.
The input file may contain several data sets. Each data set consists of two integers l (0l6) and c (1c4). The first integer l represents the side length of the triangle formed by slabs of stone. The second integer c represents the number of the kinds of the colors. The input file is terminated by l = 0.
For each data set, compute s, the number of the coloration methods without any two contiguous stones painted with the same color. If the colors given are insufficient to paint the slabs of stone, the answer should be 0. Output your answer as a single integer on a line by itself.
Note: You are required to tell him the exact answers, not the floatingpoint values.
2 3 3 3 0 0
24 528
______________________________________________________ 2030false
In such a demanding age, after working busily day after day, undoubtedly people would expect to enjoy their leisure time. What do they want to do first? It's the trip. Nowadays, in the eyes of a traveler who hopes to visit tourist attractions all over the country, the world is wonderful. Since there are so many travel agencies, if he wants to participate in an organized trip, he may choose any of them. But for a travel agency, the competition seems to be much more ruthless, for he has so many rivals in scrambling for the tourists.
Company trip center is one of those unfortunate travel agencies. After investigating from the questionnaires, the agent has found out that there are some tourists who do not get along with each other, so he has to choose some of them to organize a trip group. But he had made many mistakes in choosing those members before, and they caused many of his customers shift to his rivals. Although he could not tell exactly how many rivals he has, he knows clearly that his profits have diminished terribly. So he decides to take action to change the situation.
Company trip center pays attention to that problem at the beginning. Initially the agent does not know what tourists do not like each other, but after discussing with those tourists, he is able to acquire the information. So he will be able to form a trip group from some of those tourists in which no one is unwilling to get along with others. If company A could make a wise decision, there will be maximum number of tourists in this group, which will undoubtedly bring the biggest profits to him. What a great idea, isn't it?
You are required to write a program for company trip center to solve the problem. The solution will exist for sure. After writing such a program, you will get an acknowledgement from him.
The input file for this problem will consist of multiple test cases. The first line of each test case contains an integer n (n50), which specifies the number of tourists participating in the trip group. A value of 0 for the integer n indicates the end of input, and this test case should not be processed. Each line in the following n lines contains n characters without any separators. Each character should be either ``1" or ``0", no characters else will appear in the input file. The character ``1" means that the two tourists could not get along well with each other, so you shouldn't arrange them in one trip group. And the character ``0" means they will make no difficulty to join the same group. For example, if the 2nd characte r in the 1st line is ``1", the trip group may comprise either the 1st tourist or the 2nd tourist, if the character is ``0", the trip group may comprise both of them.
Assumption: Obviously, a tourist could not be unwilling to get along with himself. So you may
assume the corresponding character will always be ``0". If a tourist does not wish to get along
with another one, the latter will be unwilling with the former either. You may assume the data in
the input file appear conjugated.
For each test case, your program should output one integer in a line, which specifies the maximum tourists in the trip group. No more white spaces or blank lines in the output are allowed.
6 010001 100100 000110 011000 001001 100010 0
3
______________________________________________________ 2031false
Mr. White, a fat man, now is crazy about a game named ``Dance, Dance, Revolution". But his dance skill is so poor that he could not dance a dance, even if he dances arduously every time. Does ``DDR" just mean him a perfect method to squander his pounds? No way. He still expects that he will be regarded as ``Terpsichorean White" one day. So he is considering writing a program to plan the movement sequence of his feet, so that he may save his strength on dancing. Now he looks forward to dancing easily instead of sweatily.
``DDR" is a dancing game that requires the dancer to use his feet to tread on the points according to the direction sequence in the game. There are one central point and four side points in the game. Those side points are classified as top, left, bottom and right. For the sake of explanation, we mark them integers. That is, the central point is 0, the top is 1, the left is 2, the bottom is 3, and the right is 4, as the figure below shows:
At the beginning the dancer's two feet stay on the central point. According to the direction sequence, the dancer has to move one of his feet to the special points. For example, if the sequence requires him to move to the top point at first, he may move either of his feet from point 0 to point 1 (Note: Not both of his feet). Also, if the sequence then requires him to move to the bottom point, he may move either of his feet to point 3, regardless whether to use the foot that stays on point 0 or the one that stays on point 1.
There is a strange rule in the game: moving both of his feet to the same point is not allowed. For instance, if the sequence requires the dancer to the bottom point and one of his feet already sta ys on point 3, he should stay the very foot on the same point and tread again, instead of moving the other one to point 3.
After dancing for a long time, Mr. White can calculate how much strength will be consumed when he moves from one point to another. Moving one of his feet from the central point to any side points will consume 2 units of his strength. Moving from one side point to another adjacent side point will consume 3 units, such as from the top point to the left point. Moving from one side point to the opposite side point will consume 4 units, such as from the top point to the bottom point. Yet, if he stays on the same point and tread again, he will use 1 unit.
Assume that the sequence requires Mr. White to move to point 1 2 2 4. His feet may stays on (point 0, point 0) (0, 1) (2, 1) (2, 1) (2, 4). In this couple of integers, the former number represents the point of his left foot, and the latter represents the point of his right foot. In this way, he has to consume 8 units of his strength. If he tries another pas, he will have to consume much more strength. The 8 units of strength is the least cost.
The input file will consist of a series of direction sequences. Each direction sequence contains a sequence of numbers. Ea ch number should either be 1, 2, 3, or 4, and each represents one of the four directions. A value of 0 in the direction sequence indicates the end of direction sequence. And this value should be excluded from the direction sequence. The input file ends if the sequence contains a single 0.
For each direction sequence, print the least units of strength will be consumed. The result should be a single integer on a line by itself. Any more white spaces or blank lines are not allowable.
1 2 2 4 0 1 2 3 4 1 2 3 3 4 2 0 0
8 22
______________________________________________________ 2032false
Since ancient time, people have been dreaming of flying in the sky. Eventually, the dream was realized in the 20th century. Nowadays, the airplane becomes a useful vehicle that is used frequently in our daily life.
But before the dream came true, a large number of people had tried to design the aircrafts. One of those aircrafts, which is called ``helicopter" in modern time, can be traced back to the blueprint of the aircraft designed by Leonardo da Vinci. But the helicopter was not effective enough till this century.
Since the helicopter rises through the updraft generated by the airscrew, it is very important for it to keep balance. Even for the latemodel helicopters, the loads are required to be distributed evenly, so that the center of gravity of the helicopter lies just underneath the airscrew. It is one of the most important requirements for it in flight.
Now, you are requested by an airline company to write a program for a passenger transport helicopter. The program may arrange a seat for each passenger automatically so that the center of gravity of the helicopter should be located underneath the airscrew as dose as possible. The seats in the helicopter and the airscrew are designed as the figure below.
You may assume the distance of the adjoining seats is 1 unit, and the airscrew occupies a seat. A seat along with a passenger on it will generate a transverse mome nt and a longitudinal moment. The transverse moment, Mv_{i}, is the weight of a passenger on the seat multiplied by the transverse distance from the seat to the airscrew. The longitudinal moment, Mh_{i}, is the weight of a passenger on the seat multiplied by the longitudinal distance. If the transverse moments generated by the passengers on the left are assumed to be positive, the moments by the passengers on the right will be negative. Also, if the longitudinal moments generated by the passengers in front are assumed to be positive, the moments by the passengers on the back will be negative. That is, the moments may counteract with each other. You may use the formula below to figure out the composition of moments.
If M = 0, the center of gravity of the helicopter lies just underneath the airscrew.
You are required to arrange the seats of 8 passengers according to their weights to locate the center of gravity underneath the airscrew as far as possible. That is, the value of M should be minimum.
The input file may contain several test cases. Each test case consists of eight integers in lines, which represent the weights of those passengers. The end of input is signified by the test case in which the weights are all 0. And this test case should not be processed.
The output for each test case should include a line contains a real number which tells the composition of moments, M, in the optimal arrangement. The output of the composition of moments should be accurate to 3 decimal places. And you should not print any more white spaces or blank lines in the output.
1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0
0.000
______________________________________________________ 2033false
Introduction
The cards originated when a psychic named Orlan modified these tarot cards for games. The game became popular with soldiers passing time between battles. As its popularity spread, each region developed its own rules and picture variations.
Diagram
Battle Area
Basic Rules
There are two players in the game.
One of them is the red player, and the other is the blue one. They place their own cards on the battle area in turn, the red player places red cards while the blue player places blue cards. Placing a card on the location of the area that has a card is not allowed. A Card in the battle area will be turn over if its value on side adjacent to new card is less than new card's value on side adjacent to it. That is, the card's color will be changed, and it will belong to the other player. For example, as the figure shows, assume a red card has been placed on the battle area, and a blue one is now placed on the area adjacent to the right side of the red one. Since the value of the left side of the old card is 2, and the value of the right side of the new card is 7, the red card will be turned over to be a blue one, and it belongs to the blue player. When all 9 areas are filled, the outcome of the game is judged. If the player who put first card has 5 cards in battle area, it's a tie. If he has more cards, he wins the game. But if the amount of his cards is less than 5, unfortunately, he is defeated.
Note: Only the card is being placed on the battle area may turn over those that have been already placed on the area. It will not be turned over by the old ones. Remember that the new card can only turn over opponents' cards.
Same Rule
Same rule will turns over cards that have same values on 2 or more sides. As the figure shows, two red cards have already been placed on the battle area. The value of the down side of the up card is 4, and that of the right side of the left card is 1. If a blue card whose up side is 4 and right side is 1 is placed on the area, while it's adjacent to the down side of the up one and adjacent to the right side of the left one, both of the red cards will be turned over.
Note: Only adjacent cards that belong to the opponent will be turned over. In the example above, if the up card is blue, the blue card to be placed on the battle area will turn over the left red one, but not the up blue one.
Plus Rule
Plus Rule means that cards adding to the same value on 2 or more adjacent sides will be turned over. As the figure shows, two red cards have been placed on the area. The value of the up one's down side is 3, and that of the left one's right side is 5. If a blue card whose up side is 4 and left side is 2 is placed on the area, while it's adjacent to the down side of the up one and adjacent to the right side of the left one, both of the red cards will be turned over. Since both of the sum values are 7.
Note: Only adjacent cards that belong to the opponent will be turned over. In the example above, if the up card is blue, the blue card to be placed on the battle area will turn over the left red one, but not the up blue one.
Combo Rule
Cards turned over using Same Rule or Plus Rule turn over adjacent cards in Combo Rule . As the figure shows, a red card and two blue cards are on the battle area. The value of the left side of the red one is 2, and that of the down side is 4. And the red one is placed in the top left corner. A blue card whose left side is 3 is adjacent to the right side of the red one, and another blue card whose up side is 1 is adjacent to the down side of the red one. Assume those two cards are just turned over to be blue by Same Rule or Plus Rule by another card, using Combo Rule , the red one will be turned over, because the value of the right blue card's left side is larger than the value of the red one's right side (3 > 2), although the value of the down blue card's up side is less than the value of the red one's down side (1 < 4).
Note: In the example above, Combo Rule is used, not Plus Rule. If only the right blue card is just turned over by Same Rule or Plus Rule, using Combo Rule, the red one will be turned over (3 > 2). If only the down blue card is just turned over by Same Rule or Plus Rule, using Combo Rule, the red one will not be turned over (1 < 4).
Same Wall Rule
Same Wall Rule uses Battle Area Wall (the frame) as one of card's 4 sides when using Same Rule . The value of the wall on any sides may be assumed to be 10. That is, the card that is adjacent to the frame may be turned over using Same Wall Rule.
Elemental Rule
Elemental Rule will change the value of a card depending on the elemental property, as the figure shows. When a card and a slot match elemental properties, the value of the four sides will be increased by 1. If elements don't match, the value of the four sides of the card will be decreased 1 from the original value. When a card has elemental property but the slot doesn't, the values don't change, but if the slot has elementary property while the card doesn't, it's considered a mismatch (i.e. values will be decreased by 1).
You are required to write a program to judge the outcome of the game according to the rules above, and tell us whether the game is a tie. If it isn't, please inform us the winner and the number of cards the players have.
There are data groups of several card games in one input file. Each card game will begin with a line consists of 5 integers, which tell whether the rules above will be adopted respectively. Those integers should be either 1 or 0. If an integer is 1, the corresponding rule will be adopted. Otherwise, the rule will be disabled. Those 5 integers stand for, in order, basic rules, same rule, plus rule, combo rule, and same wall rule. The end of input is marked by the card game in which basic rules are disabled. And this card game should not be processed. If the game does not indicate the end of the input, there will be 3 following lines, which tell the elemental properties of the battle area. Each line contains 3 integers from 0 to 9. The 3 x 3 array of integers defines the locations of the battle area. Each location's elemental property is described by the corresponding integer. A value of 0 indicates that the corresponding location has no elemental property. While all of the 9 locations do not have elemental properties, elemental rule is disabled. Otherwise, elemental rule will be adopted. The following are 9 lines of integers, each of them tells the information of a card to be placed on the battle area by one of the players. A card in described by 9 integers. The first two integers are x and y (1x, y3), indicating the row and column of the location on which the card will be placed. The re mains are, in order, u, l, d, r, and e(1u, l, d, r10, 1e9). The integers u, l, d and r represent the values of the up side, left side, down side and right side of the card, and the integer e represents the elemental property of the card.
Assumptions:
For each card game, show the outcome according to the rules above. The first line of the outcome contains 3 integers a, b, c, indicating the winner and the cards the players hold finally. The integer a represents the number of the player 1's cards, and b represent the number of the player 2's cards. If the player 1 wins the game, c = 1; if he loses, c = 2; and if it's a tie, c = 0. The following 3 lines contain 3 integers each, describing the results of the battle area. Those integers are from 1 to 2. If the location of the battle area has a card owned by player 1, print 1 at the corresponding location. If it has a card owned by player 2, print 2 accordingly.
1 1 1 1 0 0 0 0 3 0 0 0 0 0 1 1 1 2 3 4 1 1 2 4 5 3 3 2 2 1 3 4 5 3 3 2 2 4 3 7 8 4 3 3 1 2 3 4 5 2 3 5 8 1 6 6 1 3 2 1 1 3 7 3 1 3 3 3 3 8 3 2 8 3 2 1 9 0 0 0 0 0
3 6 2 2 2 1 2 1 2 2 1 2
______________________________________________________ 2034false
John Smith, who is a member of Academy of Cold Manager (ACM), is in charge of a largescale cold store. For him, it's a troublesome job. Whenever the temperature in the cold store is too hot or too cold for a long time, the goods will be damaged. And poor Mr. Smith will have to compensate for the loss of the store.
Therefore, Mr. Smith has installed an automatic temperature control system in the store. The system may control the temperature according to the input polynomial and the start time. At each moment, it tries to adjust the temperature equal to the value of the polynomial function. But Mr. Smith still feels worried. Since he could not know the effect beforehand how the system will regulate. At such a worrisome moment, it's lucky for him to call to remembrance that you, an excellent programmer, are willing to offer a program to help him. Making use of this program, he may simply input the polynomial and the parameters of the start time and the end time, and then he will be aware of the average temperature during this period. Now he is relieved from such a bothersome job.
The input file may contain several data sets. Each data set begins with a line containing an integer n (n < 100), which specifies the highest power of the polynomial. A value of 0 for the power indicates the end of input, and this data set should not be processed. In each data set, the following line contains n + 1 real numbers, which tell the coefficients of the polynomial. The sequence of those coefficients is arranged according to the power of items from high to low in the polynomial. If an item of the polynomial does not exist, the corresponding coefficient is 0. And then follows a line consists of 2 real numbers s and e(s < e), indicating the start time and the end time.
For each data set, compute t, the average temperature of the input polynomial from the start time to the end time. Print your answer as a single real number accurate to 3 decimal places on a line by itself. You should not print any more white spaces or blank lines in the output.
2 1.0 0.0 0.0 0.0 1.0 0
0.333
______________________________________________________ 2035false
A monocycle is a cycle that runs on one wheel and the one we will be considering is a bit more special. It has a solid wheel colored with five different colors as shown in the figure:
The colored segments make equal angles (72^{o}) at the center. A monocyclist rides this cycle on an M x N grid of square tiles. The tiles have such size that moving forward from the center of one tile to that of the next one makes the wheel rotate exactly 72^{o} around its own center. The effect is shown in the above figure. When the wheel is at the center of square 1, the midpoint of the periphery of its blue segment is in touch with the ground. But when the wheel moves forward to the center of the next square (square 2) the mid point of its white segme nt touches the ground.
Some of the squares of the grid are blocked and hence the cyclist cannot move to them. The cyclist starts from some square and tries to move to a target square in minimum amount of time. From any square either he moves forward to the next square or he remains in the same square but turns 90 left or right. Each of these actions requires exactly 1 second to execute. He always starts his ride facing north and with the mid point of the green segment of his wheel touching the ground. In the target square, too, the green segment must be touching the ground but he does not care about the direction he will be facing.
Before he starts his ride, please help him find out whether the destination is reachable and if so the minimum amount of time he will require to reach it.
The input may contain multiple test cases. The first line of each test case contains two integers M and N (1M, N25) giving the dimensions of the grid. Then follows the description of the grid in M lines of N characters each. The character `#' will indicate a blocked square, all other squares are free. The starting location of the cyclist is marked by `S' and the target is marked by `T'.
The input terminates with two zeros for M and N.
For each test case in the input first print the test case number on a separate line as shown in the sample output. If the target location can be reached by the cyclist print the minimum amount of time (in seconds) required to reach it exactly in the format shown in the sample output, otherwise, print ``destination not reachable".
Print a blank line between two successive test cases.
1 3 S#T 10 10 #S.......# #..#.##.## #.##.##.## .#....##.# ##.##..#.# #..#.##... #......##. ..##.##... #.###...#. #.....###T 0 0
Case #1 destination not reachable Case #2 minimum time = 49 sec
______________________________________________________ 2036false
My little sister had a beautiful necklace made of colorful beads. Two successive beads in the necklace shared a common color at their meeting point. The figure below shows a segment of the necklace:
But, alas! One day, the necklace was torn and the beads were all scattered over the floor. My sister did her best to recolle ct all the beads from the floor, but she is not sure whether she was able to collect all of them. Now, she has come to me for help. She wants to know whether it is possible to make a necklace using all the beads she has in the same way her original necklace was made and if so in which order the bids must be put.
Please help me write a program to solve the problem.
The input contains T test cases. The first line of the input contains the integer T.
The first line of each test case contains an integer N (5N1000) giving the number of beads my sister was able to collect. Each of the next N lines contains two integers describing the colors of a bead. Colors are represented by integers ranging from 1 to 50.
For each test case in the input first output the test case number as shown in the sample output. Then if you apprehend that some beads may be lost just print the sentence ``some beads may be lost" on a line by itself. Otherwise, print N lines with a single bead description on each line. Each bead description consists of two integers giving the colors of its two ends. For 1iN  1, the second integer on line i must be the same as the first integer on line i + 1. Additionally, the second integer on line N must be equal to the first integer on line 1. Since there are many solutions, any one of them is acceptable.
Print a blank line between two successive test cases.
2 5 1 2 2 3 3 4 4 5 5 6 5 2 1 2 2 3 4 3 1 2 4
Case #1 some beads may be lost Case #2 2 1 1 3 3 4 4 2 2 2
______________________________________________________ 2037false
A digital river is a sequence of numbers where the number following n is n plus the sum of its digits. For example, 12345 is followed by 12360, since 1 + 2 + 3 + 4 + 5 = 15. If the first number of a digital river is k we will call it river k.
For example, river 480 is the sequence beginning {480, 492, 507, 519,...} and river 483 is the sequence beginning {483, 498, 519,...}.
Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values. For example: river 480 meets river 483 at 519, meets river 507 at 507, and never meets river 481.
Every digital river will eventually meet river 1, river 3 or river 9. Write a program that can determine for a given integer n the value where river n first meets one of these three rivers.
The input may contain multiple test cases. Each test case occupies a separate line and contains an integer n (1n16384). A test case wit h value of 0 for n terminates the input and this test case must not be processed.
For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line ``first meets river x at y". Here y is the lowest value where river n first meets river x (x = 1 or 3 or 9). If river n meets river x at y for more than one value of x, output the lowest value.
Print a blank line between two consecutive test cases.
86 12345 0
Case #1 first meets river 1 at 101 Case #2 first meets river 3 at 12423 ______________________________________________________ 2038falseBob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?
Your program should find the minimum number of soldiers that Bob has to put for a given tree.
For example for the tree:
the solution is one soldier (at the node 1).
Input
The input file contains several data sets in text format. Each data set represents a tree with the following description:The node identifiers are integer numbers between 0 and n1, for n nodes (0 < n ≤ 1500). Every edge appears only once in the input data.the number of nodes the description of each node in the following format:
node_identifier:(number_of_roads) node_identifier1 node_identifier2 node_identifiernumber_of_roads
or
node_identifier:(0)
Output
The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers).
Sample Input
4 0:(1) 1 1:(2) 2 3 2:(0) 3:(0) 5 3:(3) 1 4 2 1:(1) 0 2:(0) 0:(0) 4:(0)
Sample Output
1 2______________________________________________________ 2039false
A company pays different hourly wages for different job types. Each week the company keeps evidence of the total number of work hours for every job type and the total amount paid to all employees for that week. In different weeks different job types can be accomplished. The hourly wage for any job type in the same company remains unchanged. The hourly wage for any job type is a positive integer and the ratio between the maximum wage and the minimum wage is less than 6.
You are asked to write a program that computes the hourly wage for every job type using the data collected a period of time (one or several weeks). The number of job types is limited to 200 and the number of weeks in one data set is limited to 50.
Input
The input file contains several data sets in text format. The format for the data set is:The format of the information for a week is the following:The number of lines for the data set; information_for__one_or_more_weeks The job type is represented as a string of characters (limited to 20). The number of hours is a positive integer (smaller than 1E5). The total paid is a positive integer (smaller than 2E10).job_type1 number_of _hours1 job_type2 number_of _hours2 job_type3 number_of _hours3 ... . total_paid ( the dot marks the ending of info for a week) Output
The program should write to standard output (for every job type involved in the data set) a line containing the job type and the hourly wage. The output for a data set ends with a line containing a dot.If the program cannot compute a unique hourly wage for every job type it will print "Incomplete data" and if it cannot compute an integer hourly wage it will print "Inconsistent data"
Sample Input
5 job1 6 job2 5 job8 4 job10 3 . 100 13 job3 1 job2 2 . 40 job1 3 job2 1 . 100 job1 1 job3 2 job2 3 . 100 job1 1 job2 5 . 80Sample Output
Incomplete data . job3 20 job2 10 job1 30 .______________________________________________________ 2040false
Write a program that, given a natural number N between 0 and 4999 (inclusively), and M distinct decimal digits X_{1},X_{2}...X_{M} (at least one), finds the smallest strictly positive multiple of N that has no other digits besides X_{1},X_{2}...X_{M} (if such a multiple exists).
Input
The input file has several data sets separated by an empty line, each data set having the following format:On the first line  the number N On the second line  the number M On the following M lines  the digits X_{1},X_{2}...X_{M}. Output
For each data set, the program should write to standard output on a single line the multiple, if such a multiple exists, and 0 otherwise.Sample Input
22 3 7 0 1 2 1 1Sample Output
110 0______________________________________________________ 2041false
In the second year of the university somebody started a study on the romantic relations between the students. The relation romantically involved is defined between one girl and one boy. For the study reasons it is necessary to find out the maximum set satisfying the condition: there are no two students in the set who have been romantically involved. The result of the program is the number of students in such a set.
Input
The input file contains several data sets in text format. Each data set represents one set of subjects of the study, with the following description:The student_identifier is an integer number between 0 and n1, for n subjects.the number of students the description of each student, in the following format student_identifier:(number_of_romantic_relations) student_identifier1 student_identifier2 student_identifier3...
or
student_identifier:(0)
Output
For each given data set, the program should write to standard output a line containing the result.
Sample Input
7 0: (3) 4 5 6 1: (2) 4 6 2: (0) 3: (0) 4: (2) 0 1 5: (1) 0 6: (2) 0 1 3 0: (2) 1 2 1: (1) 0 2: (1) 0
Sample Output
5 2______________________________________________________ 2042false
Write a program that performs symbolic derivation f(x) = df(x)/dx of a given function f(x). The function f(x) is defined by an expression which may contain the following operations: + (addition),  (subtraction), * (multiplication), / (division), and ln (natural logarithm). Besides, the operands may be the variable x and numerical constants. The expression may contain arbitrarily nested subexpressions in parentheses ( ).
The expression is given in a usual, infix form, such as:
(2*ln(x+1.7)x*x)/((7)+3.2*x*x)+(x+3*x)*x
Numerical constants have the form d.d, with an optional sign (+ or ), where the number of digits both in integer and decimal parts are arbitrary. The input expression is guaranteed to be correct (no syntax error can occur).
The output expression should be written in infix form. It should not be optimized for human reading. This means, it can contain redundancies, such as 0*x, 1*x, 0+x, etc. The derivation should be performed using the following rules:
The operators * and / are of higher priority than the operators + and . Parentheses may change the priorities as usually. The operators +, , *, and / are leftassociative, meaning that they group from left to right:
a*b*c = (a*b)*c, a/b/c = (a/b)/c, a/b*c = (a/b)*c, etc.The rules for derivation are: (a + b)' = a' + b' (a  b)' = a'  b' (a * b)' = (a' * b + a * b') (a / b)' = (a' * b  a * b') / b^2 (Note: use b^2 and not (b*b) for presentation) ln(a)' = (a')/(a) x' = 1 const' = 0While producing the symbolic derivation, use parentheses for output strictly as stated in the previous rule. Do not perform presentation optimizations, such as 0*a = 0, 1*a = a, etc.
Input
The input is a textual file which has one f(x) definition per line. The input lines do not have blanks.
Output
The output should contain lines with corresponding symbolic derivations f=df/dx, one line for each f. The strings representing f(x) and f (x) are guaranteed to have no more than 100 characters.
Sample Input
x*x/x 45.78*x+x 2.45*x*x+ln(x3)
Sample Output
((1*x+x*1)*xx*x*1)/x^2 (0*x45.78*1)+1 ((0*x2.45*1)*x2.45*x*1)+(10)/(x3)______________________________________________________ 2043false
A specialist in VLSI design testing must decide if there are some components that cover each other for a given design. A component is represented as a rectangle. Assume that each rectangle is rectilinearly oriented (sides parallel to the x and y axis), so that the representation of a rectangle consists of its minimum and maximum x and y coordinates.
Write a program that counts the rectangles that are entirely covered by another rectangle.
Input
The input file contains the text description of several sets of rectangles. The specification of a set consists of the number of rectangles in the set and the list of rectangles given by the minimum and maximum x and y coordinates separated by white spaces, in the format:nr_rectangles
xmin_{1} xmax_{1} ymin_{1} ymax_{1}
xmin_{2} xmax_{2} ymin_{2} ymax_{2}
...
xmin_{n} xmax_{n} ymin_{n} ymax_{n}Output
The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the number of rectangles that are covered).Sample Input
3 100 101 100 101 0 3 0 101 20 40 10 400 4 10 20 10 20 10 20 10 20 10 20 10 20 10 20 10 20Sample Output
0 4______________________________________________________ 2044false
Consider a group of N students and P courses. Each student visits zero, one or more than one courses. Your task is to determine whether it is possible to form a committee of exactly P students that satisfies simultaneously the conditions:
every student in the committee represents a different course (a student can represent a course if he/she visits that course) each course has a representative in the committee
Input
The first line of the input file contains the number of the data sets. Each data set is presented in the following format:P N Count_{1} Student_{1 1} Student_{1 2} Student_{1 Count1} Count_{2} Student_{2 1} Student_{2 2} Student_{2 Count2} .. Count_{P} Student_{P 1} Student_{P 2} Student_{P CountP}The first line in each data set contains two positive integers separated by one blank: P (1≤P≤100)  the number of courses and N (1≤N≤300)  the number of students. The next P lines describe in sequence of the courses from course 1 to course P, each line describing a course. The description of course i is a line that starts with an integer Count_{i} (0≤Count_{i}≤N) representing the number of students visiting course i. Next, after a blank, youll find the Count i students, visiting the course, each two consecutive separated by one blank. Students are numbered with the positive integers from 1 to N. There are no blank lines between consecutive sets of data. Input data are correct.
Output
For each input data set the program prints on a single line YES if it is possible to form a committee and NO otherwise. There should not be any leading blanks at the start of the line.
Sample Input
2 3 3 3 1 2 3 2 1 2 1 1 3 3 2 1 3 2 1 3 1 1
Sample Output
YES NO______________________________________________________ 2045false
Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u,v) the program determines the closest common ancestor of u and v in the tree. The closest common ancestor of two nodes u and v is the node w that is an ancestor of both u and v and has the greatest depth in the tree. A node can be its own ancestor (for example in Figure 1 the ancestors of node 2 are 2 and 5).
Input
The data set, which is read from a text file, starts with the tree description, in the form:nr_of_vertices vertex:(nr_of_successors) successor_{1} successor_{2} ... successor_{n}where vertices are represented as integers from 1 to n. The tree description is followed by a list of pairs of vertices, in the form:nr_of_pairs (u v) (x y)The input file contents several data sets (at least one). Note that whitespaces (tabs, spaces and line breaks) can be used freely in the input.
Output
For each common ancestor the program prints the ancestor and the number of pair for which it is an ancestor. The results are printed on the standard output on separate lines, in to the ascending order of the vertices, in the format:ancestor:times
Sample Input
5 5:(3) 1 4 2 1:(0) 4:(0) 2:(1) 3 3:(0) 6 (1 5) (1 4) (4 2) (2 3) (1 3) (4 3)
Sample Output
2:1 5:5______________________________________________________ 2046false
Modulo arithmetic is an interesting topic as there are dierent ways of computing the results eectively. Consider the multiple exponentiation problem, which computes the following modulo arithmetic:
y = a^{pp...p} mod nwhere there are m exponentiations. The numbers a, p, m and n are all positive integers greater than 1 and less than 65535. Furthermore, a and p are prime numbers such that n2a and n2p. This ensures the existence of useful discrete logarithms.Input
Your program should be structured as a loop to read in lines of 4 numbers, in the order of a, p, m and n, from the standard input.
In your program, no error checking is required for input.
Output
Write a program to compute the value of y.
Print out the results to standard output.
Sample Input
3315 3325 3335 47 47 167 47 47 267 47 47 367 32719 54323 99 65399Sample Output
2 2 2 6 19 54 46184______________________________________________________ 2047false
Complex numbers can be useful in manycontext. Here wewould like to perform complex arithmetic and evaluate an expression containing complex numbers. Each simple complex number is of the form a + bi or a  bi, or simply bi, where a and b are positive integers. Thus  a + bi and  a  bi are illegal forms. There are five operators in complex expressions: ``+", ``", ``*", ``/" and ``%", where ``%" is a unary postfix operator meaning conjugate. In other words, (a + bi)% = a  bi and (a  bi)% = a + bi. There is no unary minus operator.
In this problem, the precedence rules of the operators are slightly different from those in common sense. In particular, the conjugate operator ``%" will take the highest precedence. Both ``+" and ``" will take the next precedence. Finally, ``*" and ``/" will take the lowest precedence. Operators with the same precedence are evaluated in a lefttoright order. In other words, subexpressions within brackets will be evaluated first. The conjugate will be evaluated before ``+" and ``", which again will be evaluated before ``*" and ``/". Each expression will be terminated by the ``=" operator that will force the expression to be evaluated.
Operands to the expressions can be either a positive number or a simple complex number, but not ``complicated" complex numbers. It is possible that during evaluation of division, complex numbers that are not simple may be resulted. In this application, you are required to express ``complicated" complex numbers in the form of [a + bi]/r or [a  bi]/r, where a and b are nonnegative integers and r is a nonzero integer (may be negative). Note that (a + bi)/(c + di) = [(ac + bd )+ (bc  ad )i]/(c^{2} + d^{2}).
Input
Write a program to read in a sequence of lines from the standard input file containing one or more expressions, each ended with `='.
In your program, no error checking is required for input. For simplicity, each line can be assumed to contain at most 80 characters and that during all intermediate steps, the numerator and denominator will not fall beyond the range of a largest signed integer.
Output
For each expression, evaluate and print the result in the form of a ``complicated" complex number, [a + bi]/r or [a  bi]/r.
The result is to be printed to the standard output.
Sample inputs and outputs of the program are as follows:
Sample Input
3+2i * 4 + i= 2+i*2i = (2 + 3 i) /(7+i)% = (5+3i)/(1+3i)% = (1+i)%/3+ i *2i+3 = ((1+i)%/3+i*2i+3)+(3i+1*(2i*2i%/3)) =Sample Output
[10+11i]/1 [5+0i]/1 [11+23i]/50 [29i]/5 [311i]/5 [61+43i]/15______________________________________________________ 2048false
Johnny is the manager of a moving company. As business is improving by the days and Johnny would like to optimize the operations and profits of the company, he decides to automate manpower planning and scheduling. The main factors to consider in such a planning exercise include what major furniture items are to be moved and the manpower requirement(suchasnumber of movers) to moveeach of such items. Johnny's customers are usually corporate clients who are demanding and always liketohave the moving job completed within a certain amount of time. Johnny comes to you for help for such a planning and scheduling system.
Write a program to read in a sequence of job descriptions from a standard input file. Each job description consists of:
Each record contains three fields:
Time is specified in minutes.
Each job description should generate the following output:
Each schedule consists of a sequence of start times on one line. The times should be enclosed in square brackets and separated by commas. Each start time is for each furniture item. The start times should be printed in the exact order that the items are read in. The time should be in the number of minutes since the start of the moving job (at time 0).
Note that the many possible schedules of a job must be ordered ascendingly according to the lexicographical ordering defined as follows. We consider a schedule for n items to be a string of n integers
A string t_{1},..., t_{n} is less than another string s_{1},..., s_{n} if there exists 1kn such that
The sample input specifies two jobs. The first job must be completed within an hour and consists of four major furniture pieces. The first piece is a piano requiring thirty minutes and three movers to move. The other items can be interpreted similarly. The second specification begins immediately after the first specification. The second job is very similar to the first job except for a slight difference in manpower requirement for the table.
Output for different jobs should be separated by a blank line. The job output should also be ordered in exactly the same way that they are specified in the input file. The output should be printed to the standard output file.
You can safely assume that all items can be moved at the same time if enough manpower is assigned. You also need to consider only jobs with at most ten furniture items. Each job spans across at most one hour. Each furniture item requires at least one mover.
The output format up to the schedules for each job is pretty straight forward. For space reason, we cannot give you all the possible schedules, but they must respect the same lexicographical ordering defined above. For example, in the first schedule of the first job, it means that the piano should be handled at the beginning of the move, the chair and the table both after 30 minutes, and the bed after 45 minutes. The first schedule of the first job is lexicographically less than the second schedule of the same job since
This lexicographical ordering is maintained for all schedules of both the first and second jobs. Note that a blank line is printed between the output of the first job and that of the second job.
You can safely assume that there are at least one item to move in each moving job, and that all job specifications are doable when given enough manpower resources. Your program should also run with reasonable eficiency.
60 4 piano 30 3 chair 10 1 bed 15 3 table 15 2 60 4 piano 30 3 chair 10 1 bed 15 3 table 15 3
Job description: [piano,30,3] [chair,10,1] [bed,15,3] [table,15,2] Number of movers required: 3 [0,30,45,30] [0,31,45,30] ... Job description: [piano,30,3] [chair,10,1] [bed,15,3] [table,15,3] Number of movers required: 4 [0,0,30,45] [0,0,45,30] [0,1,30,45] ... [30,49,15,0] [30,50,0,15] [30,50,15,0]
______________________________________________________ 2049false
In order to guarantee the effectiveness of a communication network, we will monitor each communication line to make sure it works properly. We will use a device, called Network Watcher, for this purpose. Once a Network Watcher is installed on a site, it can monitor all communication lines connected to the site. To be cost effective, we wish to use the smallest number of Network Watchers to monitor all communication lines in a communication network. As you may have guessed, it is extremely dificult to determine such a number for a network.
Fortunately, the problem you are facing seems easier: there are only K Network Watchers available. Therefore if a network requires more than K Network Watchers, we have to use other means to monitor the communication lines. Your task is to determine if a given network requires at most K Network Watchers to monitor all communication lines; if so, find at most K sites to install Network Watchers to monitor all communication lines in the network. Call this the K Network Watcher problem. The really good news for you is that due to budget constraints, K is at most 10. Furthermore, the number N of sites in a network is at most 100.
Write a program to solve the K Network Watcher problem. You program should be eficient enough to solve the problem instances in time
Your program should read the input from the standard input. The first line of the input is the number of networks in the input. Assume that each site is represented by a unique number between 1 and N. The input for each network consists of numbers N and K, and a description of the network. The first line of input contains numbers N and K separated by exactly one blank space. It is followed by at most N lines that specify a network, and number `1' in a separate line. For site with site index i (or simply site i), there is an input line consisting of the site followed by the list of sites with larger site indices that are connected to site i, with a blank space separating every two sites. For example, the following line
1 4 2 3 6 7means that site 1 is connected to sites 2 3 4 6 and 7. If site i is not connected to any sites with larger site indices, there is no input line for site i.
Your output should be printed to the standard output. The output for each problem is a list of sites, each separated by one blank space, and should be on a separate line. The list of sites should be ordered in increasing site indices. If K Network Watchers are not enough for an input network, you just output ``Impossible".
You should note that the solution to a K Network Watcher problem is not unique. However, you are required to give only one answer.
2 8 3 1 4 2 3 6 7 2 3 4 5 6 3 5 7 6 8 1 6 3 1 4 5 2 2 6 3 3 4 6 4 5 5 6 1
1 2 3
______________________________________________________ 2050false
Consider an n x n (17n2) board of unit squares with the upperright corner square missing. Figure 1 shows some of the possible boards for n = 2, 3, and 4. The missing squares are shaded.
You are required to tile a board using triominoes (Figure 2). In this tiling two triominoes may not overlap and they must cover all the (n^{2}  1) squares.
Write a program that shows how a board could be tiled by triominoes.
Your program should read a satndard input file that contains a few lines. Each line contains an integer n. If an n by n board with a missing corner square can be tiled, your program should output the tiling by marking every square with a tile number.
Specifically, for each input number n, your program should output n lines, each line with n integers separated by a space (except for the first line, which has n  1 integers). The ith number of the jth line represents the number of the tile that covers the square in the board that is i units from the left and j units from the top. Format your output so that eachinteger occupies exactly two character spaces.
If the board cannot be tiled, your program should output ``No solution". Write your output to the standard output.
3 4 5 10
No solution 2 2 5 2 3 5 5 1 3 3 4 1 1 4 4 3 3 6 6 3 5 5 6 8 2 2 5 8 8 2 1 4 4 7 1 1 4 7 7 17 17 19 19 21 21 29 29 33 17 18 19 20 21 22 29 32 33 33 18 18 20 20 22 22 30 32 32 31 1 1 3 3 6 6 30 30 31 31 1 2 3 5 5 6 7 28 28 27 2 2 4 4 5 7 7 28 27 27 16 16 12 4 8 8 9 26 26 25 16 13 12 12 8 9 9 26 25 25 15 13 13 14 10 10 11 24 24 23 15 15 14 14 10 11 11 24 23 23
______________________________________________________ 2051false
Consider an n by n board of n^{2} squares. Each square has a pair of coordinates (x, y) where 1x, yn. Each square has two states: either ``On" or ``Off". Initially, all squares are in the ``Off" state.
For a square (i, j), its neighbors are the squares: {(i', j') 1i', j'n; i'  i, j'  j1}. For example, if n = 4, the neighbors of (4,2) are (4,1),(4,2),(3,2),(4,3). Note that (i, j) is a neighbor of itself. Define the operation toggle(i, j) that toggles the states of square (i, j)'s neighbors. That is, if a square's original state is ``On", it will be switched to ``Off" and vice versa.
Write a program that, given an n by n board of all `Off" squares, computes a shortest sequence of toggle operations that turns all the squares ``On". If no sequences can turn all the squares ``On", output ``No solution".
Specifically, your program should read astandard input file that contains a few lines. Each line contains a number n.
Your program should output a standard file, which contains n sequences (or the string ``No solution"), separated by blank lines. The ith sequence gives a solution to the toggling problem of the board specified by the ith input number n. Each sequence is a sequence of square coordinates of the form (a, b). (Note that a and b are separated by a lone comma, not any spaces.) The coordinates of squares are separated by a space. A sequence specifies the order in which the toggle operation should be applied to the squares. For example, the sequence:
(1,2) (2,3) (1,1)specifies that the toggle operations are applied to square (1,2) first, then to square (2,3), and finally to square (1,1). Figure 3 shows how the above sequence changes the states of the squares ina 3 by 3 board. (Shaded squares are ``On".)
2 3 4
(1,1) (1,2) (2,2) (2,1) (2,2) (1,3) (3,3) (3,1) (1,1) (1,1) (1,3) (1,4) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (4,1) (4,2) (4,4)______________________________________________________ 2052false
Starting from point (0,0) on a plane, we have written all nonnegative integers 0,1,2,... as shown in the figure. For example, 1, 2, and 3 has been written at points (1,1), (2,0), and (3,1) respectively and this pattern has continued.
You are to write a program that reads the coordinates of a point (x, y), and writes the number (if any) that has been written at that point. (x, y) coordinates in the input are in the range 0...5000.
The first line of the input is N, the number of test cases for this problem. In each of the N following lines, there is x, and y representing the coordinates (x, y) of a point.
For each point in the input, write the number written at that point or write "No Number" if there is none.
3 4 2 6 6 3 4
6 12 No Number
______________________________________________________ 2053false
His Excellency the ambassador of Puzzlestan to Tehran is giving a reception (party) on the occasion of Puzzlestan national day on the second of November. Ambassadors of all missions to Tehran are invited. At the entrance to reception hall each guest leaves his belongings (overcoat, hat, ..., which we will call items afterwards) with the attendant who knows the host ambassador loves puzzle games. While waiting for the reception to end, the attendant prepares a program on his laptop that helps him find what belongs to whom. He asks each guest to give some statements that:
Relates two items belonging to the same guest. Indicates two items that do not belong to the same guest.
Suppose there are N kinds of items and M guests, and assume each guest has exactly one item from each kind (i.e. each guest has one overcoat, one hat, ...). Each of N x M items is given a unique name, which is a single letter (casesensitive). We can then represent all items of kind i (1 ≤ i ≤ N) by a string of length M. We call this, ith group. For example, ith group can be ABCD. In this case, its first item is A, its second item is B, and so on.
The first line includes the number of test cases (at most 20). First line of each test case includes two positive integers; the first one being N (1 ≤ N ≤ 7), the number of item kinds, and the second is M (1 ≤ M ≤ 7), the number of guests. In each of the next N lines, there is one string of length M, representing one group (different items of the same kind). The rest of the input includes several lines of statements. Each statement is of form i j X k r, which means that the jth item of the ith group and the rth item of the kth group belong to the same guest (if X is R) or do not belong to the same guest (if X is N). The last line of each test case is a dummy statement 0 0 R 0 0.
For each test case, the program should produce M lines, line i (1 ≤ i ≤ M) starts with the letter indicating the ith member of the first group in the input test case, then the related member of the second set and so on until that of the last set. (So the letters in the first column are the same as the letters in the first group, preserving order). Output for consecutive test cases must be separated by exactly one blank line.
1 3 4 ABCD EFGH IJKL 1 1 R 3 2 1 2 N 2 2 2 2 R 3 4 1 3 R 2 3 1 1 N 2 4 3 1 R 1 3 0 0 R 0 0
AEJ BHK CGI DFL
______________________________________________________ 2054false
DDL is a very simple programming language in which variables are dynamically declared at run time. All variables in DDL are of the signed integer type within the range 9999...9999. There are up to five types of statements in a DDL program (each statement is in a separate program line, and the first statement is in line 1):
1. Dcl <id>Dcl is a keyword specifying a declaration statement. id is a single (casesensitive) letter designating a DDL variable. For example Dcl x when executed correctly, allocates memory for variable x, and sets its value to zero.2. <id> = <ic>
This is an assignment statement, where id is a DDL variable, and ic is a literal integer constant in the range (0...9999). For example x = 2000 when executed correctly, changes value of x to 2000. Note that there may be one or more number of blank characters around =, but there is no tab characters.3. Goto <label>, or Goto <id> <label>
Goto is a keyword specifying an unconditional or conditional goto statement. label is a program line's number. For example Goto 5 transfers the program execution flow to line 5 of the program, and Goto x 5 when executed correctly, trasfers the flow to line 5 iff x>0, and to the next line otherwise. The label is guaranteed to be in the range of program line numbers.4.Inc <id>, or Dec <id>
Inc and Dec are keywords specifying increment and decrement statements respectively. For example Inc x (Dec y) when executed correctly adds (substracts) 1 to (from) the value of x (y).5. End
End is a keyword specifying the end statement, whose execution stops the program.
Note that the keywords of the DDL language are caseinsensitive.
Error conditions:
When one of the following erroneous statements encounters during the program execution, an error message appears in a separate line of the output. Each error message is of the form <label> <space> <error code>. label is the line number for the erroneous statement, space is one blank character, and error code is a positive integer specified below.
1. Dcl x is erroneous if x has not been referenced (used in assignment, goto, increment or decrement) since the last time a Dcl x (declaring the same variable) statement has been executed, unless this is the first Dcl x statement being executed. In this erroneous condition, an error message indicating a repeated declaration is generated as <label> 1, where label is the program line number for the erroneous statement. Then the program flow transfers to the statement in the next program line, and any prior correctly executed declaration for x is valid.
2.Any other statement where a variable such as x is referenced (used in assignment, goto, increment or decrement) is erroneous if no Dcl x has been previously correctly executed. In this case, an error message indicating an undeclared reference is generated as <label> 2 and the program execution continues from the next line.
First line of the input file contains a single integer N indicating the number of DDL programs to follow (1 ≤ N ≤ 20). The first line of each test case contains a single integer indicating number of statements in that program which is in the range (1...100). There are no blank lines between test cases. Statements of each DDL program come one after the other in separate lines without any blank lines in between. Statements are not explicitly labeled, but they are implicitly labeled by the number of their line beginning from 1 for the first statement in each program. There is no syntax error in programs and they are guaranteed to terminate, and no overflow or underflow errors will occur during execution. In each line of the program, tokens (e.g. GOTO, =, etc.) are separated by at least one blank character. Also there may be some blank characters in the beginning or at the end of each line.
For each input DDL program, your output should start with the program number in the first line, followed by the error messages generated by the program in the order they are generated, each error message in one line. There should be no blank lines between error messages.
2 4 DCL X INC X DCL X END 9 DCL X INC X GOTO X 5 DCL Y Y = 100 DCL X DCL X Y = 50 END
1 2 5 2 7 1 8 2
______________________________________________________ 2055false
A company producing toys has a complex system to paint its products. To obtain the desired color, the product must be painted by several colors in a specified order. A product is painted by moving through color tunnels. For each color there is at least one tunnel that paints with that color, but there may be more. The tunnels are distributed in the painting area and the product must be delivered from one tunnel to another in order to be painted with the given colors. The product is at a certain point in the production plant when painting process starts and must finally be delivered to the product warehouse.
More formally, a finished uncolored product is at a certain given point (source point) and must be delivered to another given point (destination point) after being painted with different colors in a given order. There are several tunnels, each is assumed to be a line segment in the plain with a specific color. The colors of the tunnels are not necessarily distinct. Let <c_{1}, c_{2}, ..., c_{n}> be the sequence of n colors that the product is to be painted with. The product is required to pass through tunnels <t_{1}, t_{2}, ... t_{n}> such that the color of t_{i} is c_{i}. Note that it is possible to pass through a tunnel without being painted, so the mentioned <t_{1}, t_{2}, ... t_{n}> may be in fact a subsequence of the tunnels which the product passes through. The direction in which the product passes a tunnel is not important. The goal is to find the shortest path from source to destination subject to the color constraints. The path may cross itself, or even cross a tunnel. Passing twice (or more) through a tunnel is also allowed. Note that two tunnels can cross or overlap but are different.
The input file contains several test cases. The first line of the input consists of a single integer t (between 1 and 20), the number of test cases. Following the first line is the data for t test cases. The first line of each test case contains four real numbers x_{s}, y_{s}, x_{t}, y_{t}_{ }which are x and y coordinates of the source and destination respectively. The second line of the test case contains the color sequence: the first number is the length of the sequence (between 1 and 30), and the rest of the line is the sequence itself. Each color in the sequence is an integer in the range 1...100. The third line contains a single integer n in the range 1...60 which is the number of tunnels followed by n lines each containing five numbers. The first two numbers are the x and y coordinates of one end of the tunnel. The third and fourth numbers are the x and y coordinates of the other end. Coordinates are real numbers. The fifth number is an integer in the range 1...100 representing the color of the tunnel.
The output file must have t lines, each containing the minimum length of a path from source to destination subject to the constraints of the problem, with a precision of three digits after decimal point.
1 0 1.5 100 67 4 1 4 3 1 9 10 10 20 20 1 10 15 20.5 35.333 3 30 15 14.55 12.5 1 40 30 44 33 1 29 84 33 58 4 9 39 41 115 2 75 47 37 69 4 46 26 58 25 3 73 48 27 59 3
240.610
______________________________________________________ 2056false
A math instructor is too lazy to grade a question in the exam papers in which students are supposed to produce a complicated formula for the question asked. Students may write correct answers in different forms which makes grading very hard. So, the instructor needs help from computer programmers and you can help.
You are to write a program to read different formulas and determine whether or not they are arithmetically equivalent.
Single letter variables (case insensitive). Single digit numbers. Matched left and right parentheses. Binary operators +,  and * which are used for addition, subtraction and multiplication respectively. Arbitrary number of blank or tab characters between above tokens.
Note: Expressions are syntactically correct and evaluated from left to right with equal precedence (priority) for all operators. The coefficients and exponents of the variables are guaranteed to fit in 16bit integers.
Your program must produce one line for each test case. If input expressions for each test data are arithmetically equivalent, "YES", otherwise "NO" must be printed as the output of the program. Output should be all in uppercase characters.
3 (a+bc)*2 (a+a)+(b*2)(3*c)+c a*2(a+c)+((a+c+e)*2) 3*a+c+(2*e) (ab)*(ab) (a*a)(2*a*b)(b*b)
YES YES NO
______________________________________________________ 2057false
Discovery Co. ltd. builds a satellite using a new kind of an intelligent camera. The camera has special software to detect cities and roads from an image, and is also able to detect every region (which is a connected part of surface), bounded by a series of connected roads with no other region inside. Using this technology, the satellite is able to compress the picture before sending it. The compressed format of a picture is the city locations and its regions.
Discovery has launched the satellite, without testing the software completely. So, after a while, they received some buggy pictures which includes one more extra region: the outer region. The outer region is the region of the plane enclosing every other region (which has infinite area). Further analysis shows that all images sent have the following properties:
1. All cities, in the image, have at least two roads to the other cities. 2. There is a path connecting every pair of cities. 3. There is at most one road between each pair of cities. 4. Roads do not cross each other except at the cities.
Input
The first line of the input consists of a single integer N (1 ≤ N ≤ 20), which is the number of test cases. The test cases appear with no blank lines in between. The first line of each test case consists of the number of cities (between 1 and 50) followed by pairs of integers (x, y) which are location of cities (each pair in one line), followed by number of faces in a separate line (between 1 and 50), followed by face information on each line. Face information consists of number of cities making the face and the city numbers in clockwise (or counterclockwise) order.
There should be a single line containing the boundary face number for each test case, with no blank lines in between.
1 5 2 6 4 4 4 7 8 6 4 10 3 4 1 2 4 3 4 1 3 4 5 4 1 2 4 5
3
______________________________________________________ 2058false
A supermarket in Tehran is open 24 hours a day every day and needs a number of cashiers to fit its need. The supermarket manager has hired you to help him, solve his problem. The problem is that the supermarket needs different number of cashiers at different times of each day (for example, a few cashiers after midnight, and many in the afternoon) to provide good service to its customers, and he wants to hire the least number of cashiers for this job.
The manager has provided you with the least number of cashiers needed for every onehour slot of the day. This data is given as R(0), R(1), ..., R(23): R(0) represents the least number of cashiers needed from midnight to 1:00 A.M., R(1) shows this number for duration of 1:00 A.M. to 2:00 A.M., and so on. Note that these numbers are the same every day. There are N qualified applicants for this job. Each applicant i works nonstop once each 24 hours in a shift of exactly 8 hours starting from a specified hour, say t_{i} (0 ≤ t_{i} ≤ 23), exactly from the start of the hour mentioned. That is, if the ith applicant is hired, he/she will work starting from t_{i} oclock sharp for 8 hours. Cashiers do not replace one another and work exactly as scheduled, and there are enough cash registers and counters for those who are hired.
You are to write a program to read the R(i) 's for i=0...23 and t_{i}'s for i=1..N that are all, nonnegative integer numbers and compute the least number of cashiers needed to be employed to meet the mentioned constraints. Note that there can be more cashiers than the least number needed for a specific slot.
The first line of input is the number of test cases for this problem (at most 20). Each test case starts with 24 integer numbers representing the R(0), R(1), ..., R(23) in one line (R(i) can be at most 1000). Then there is N, number of applicants in another line (0 ≤ N ≤ 1000), after which come N lines each containing one t_{i }(0 ≤ t_{i } ≤ 23). There are no blank lines between test cases.
For each test case, the output should be written in one line, which is the least number of cashiers needed.
If there is no solution for the test case, you should write No Solution for that case.
1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 5 0 23 22 1 10
1
______________________________________________________ 2059false
In a newly constructed dolphin pool in the Kish island in Persian Gulf, one of the fun games is as follows: the game director throws several plastic rings in the pool such that center of no ring lies inside any other ring, and no two rings are tangent. The dolphins are trained to jump out on the directors whistle through the closed areas that are completely outside the rings, one dolphin from one such area. The dolphins jump out if and only if the number of closed areas exactly equals to the number of dolphins.
You are to write a program to given the following input/output description, finds the number of closed areas between rings to help the dolphins decide to jump out or not.
The first line includes the number of test cases (at most 20). Each test case data has an integer N (1 ≤ N ≤ 20), the number of plastic rings, in its first line. Following the first line there are N lines, each containing three integers, the first and second being the x and y coordinates of the circle of the ring, and the third is its radius. Coordinates are positive integers less than 1000 and the radius is in the range 1...100.
For each test case, there must be one line in the output including the number of closed areas in that test case.
2 4 100 100 20 100 135 20 135 100 20 135 135 20 1 10 10 40
1 0
______________________________________________________ 2060false
It's now 3002 and the Godfather Unlucky Luchiano is planning a rubbery from the Rectilinia museum. The problem is that the walls of the museum are impenetrable and the doors are guarded so his men cannot enter the museum from its doors. He is lucky that the museum has no roofs and one can enter the museum from the above. So he decides to use a device from thousands of years ago; a catapult! Using this, his men can fly and fall in some place in the museum without being caught by guards.
But another problem still exists which is a hightech laser gun that guards the museum. The laser gun is designed based on a very recent discovery that it is possible to guide the laser beam not on a straight line, but on a rectilinear path. The fact that the beam travels the shortest (possible) distance from the emission point to a target still remains. The problem is that if one land somewhere in the museum that is reachable by the laser beams, he will be immediately destroyed. Again godfather is lucky, since in the museum, there are some walls and other obstacles through which the beam cannot pass and if his men can land in the shadows of that walls, they are safe in the way that they are not destroyed by the gun right after landing and they can use their special device to disable the laser gun. As the catapult is not a very precise device, godfather wants to know the probability of landing in shadows, so he has to compute the total area of shadowy regions of the museum.
Given the layout of the museum, you have to write a program to compute the total area of the shadowy regions. Yes! This time you really HAVE TO!
As you study the layout of the museum from the top view, you find that the museum can be considered as a rectangle with some obstacles in it. The obstacles are simple polygons with sides parallel to the rectangle sides. Interior of obstacles do not overlap. The laser gun is located in the upperright corner of the museum. A laser beam is composed of a number of line segments; each is either horizontal or vertical. When the gun chooses its target, it intelligently determines a possible path to the target and fires. A possible path has the following characteristics:
It consists of only horizontal and vertical segments. It never crosses an obstacle but in some parts may be tangent to obstacle sides. It can never be tangent to two obstacle sides at one point. In the travel from the gun to the target, the beam never moves from left to right or from bottom to top (directions are relative to view of the museum from the above).
Input
The input file contains several test cases. The first line contains a single integer t (between 1 and 10), which is the number of test cases. Rest of the input file contains t test cases. The first line of each test case contains 2 positive integers, which are the length and the width of the rectangle respectively. The second line contains a single integer n, which is the number of obstacles in the museum (between 0 and 50). After it, there are n lines, which contain the obstacle data. Each obstacle data is in a single line, which begins with an integer m, which is the number of vertices of the obstacle (between 4 and 50), followed by 2m numbers, which are the x, and y coordinates of the vertices listed in clockwise order. Every coordinate in the input is a positive integer less than 1,000,000. Upperleft corner of the rectangle is the coordinate origin.
The output file must contain exactly t lines. Each line contains a single number, which is the total area of the safe regions in the test case. The output for each test case is guaranteed to fit in a 32bit integer.
1 12 8 3 8 5 1 11 1 11 5 7 5 7 4 9 4 9 2 5 2 4 0 3 3 3 3 4 0 4 4 1 4 2 4 2 6 1 6
12
______________________________________________________ 2061false
In the triangle game you start off with six triangles numbered on each edge, as in the example above. You can slide and rotate the triangles so they form a hexagon, but the hexagon is only legal if edges common to two triangles have the same number on them. You may not flip any triangle over. Two legal hexagons formed from the six triangles are illustrated below.
The score for a legal hexagon is the sum of the numbers on the outside six edges.
Your problem is to find the highest score that can be achieved with any six particular triangles.
The input file will contain one or more data sets. Each data set is a sequence of six lines with three integers from 1 to 100 separated by blanks on each line. Each line contains the numbers on the triangles in clockwise order. Data sets are separated by a line containing only an asterisk. The last data set is followed by a line containing only a dollar sign.
1 4 20 3 1 5 50 2 3 5 2 7 7 5 20 4 7 50 * 10 1 20 20 2 30 30 3 40 40 4 50 50 5 60 60 6 10 * 10 1 20 20 2 30 30 3 40 40 4 50 50 5 60 10 6 60 $
152 21 none______________________________________________________ 2062false
Password security is a tricky thing. Users prefer simple passwords that are easy to remember (like buddy), but such passwords are often insecure. Some sites use random computergenerated passwords (like xvtpzyo), but users have a hard time remembering them and sometimes leave them written on notes stuck to their computer. One potential solution is to generate "pronounceable" passwords that are relatively secure but still easy to remember.
FnordCom is developing such a password generator. You work in the quality control department, and it's your job to test the generator and make sure that the passwords are acceptable. To be acceptable, a password must satisfy these three rules:
(For the purposes of this problem, the vowels are 'a', 'e', 'i', 'o', and 'u'; all other letters are consonants.) Note that these rules are not perfect; there are many common/pronounceable words that are not acceptable.
The input consists of one or more potential passwords, one per line, followed by a line containing only the word 'end' that signals the end of the file. Each password is at least one and at most twenty letters long and consists only of lowercase letters.
For each password, output whether or not it is acceptable, using the precise format shown in the example.a tv ptoui bontres zoggax wiinq eep houctuh end
<a> is acceptable. <tv> is not acceptable. <ptoui> is not acceptable. <bontres> is not acceptable. <zoggax> is not acceptable. <wiinq> is not acceptable. <eep> is acceptable. <houctuh> is acceptable.______________________________________________________ 2063false
A simple matching game for children uses a board that is a sequence of colored squares. Each player has a game piece. Players alternate turns, drawing cards containing either one colored square or two colored squares of the same color. Players move their pieces forward on the board to the next square that matches the single color on the card, or forward to the second matching square if the card contains two colored squares, or forward to the last square on the board if there is no square matching the description above. A player wins if his piece lands on the last square of the board. It is possible for all the cards to be drawn and still not have a winner.
This problem represents colors with capital letters from AZ. Below is a diagram of a sample board.
Consider the deck of cards: R, B, GG, Y, P, B, P, RR
For 3 players, the game proceeds as follows:
Player 1 draws R, moves to 1st square Player 2 draws B, moves to 5th square Player 3 draws GG, moves to 8th square Player 1 draws Y, moves to 2nd square Player 2 draws P, moves to 11th square Player 3 draws B, moves to 9th square Player 1 draws P, moves to 4th square Player 2 draws RR, Wins! (no Rs in front of piece so it goes to last square)
Using the same board and the same deck of cards, but with 2 players, Player 1 wins after 7 cards. With 4 players, no one wins after exhausting the deck of 8 cards.
Input consists of information for one or more games. Each game starts with one line containing the number of players (14), the number of squares on the board (179), and the number of cards in the deck (1200). This is followed by a single line of characters representing the colored squares on the board. Following this are the cards in the deck, one card per line. Cards can have only a single character, or two of the same character. The end of the input is signalled by a line with 0 for the number of players  the other two values will be present but indeterminate.
2 13 8 RYGPBRYGBRPOP R B GG Y P B P RR 2 6 5 RYGRYB R YY G G B 3 9 6 QQQQQQQQQ Q QQ Q Q QQ Q 0 6 0
Player 1 won after 7 cards. Player 2 won after 4 cards. No player won after 6 cards.______________________________________________________ 2064false
Figure 1
Figure 1 shows a graphical representation of a binary tree of letters. People familiar with binary trees can skip over the definitions of a binary tree of letters, leaves of a binary tree, and a binary search tree of letters, and go right to The problem.
A binary tree of letters may be one of two things:
In the graphical representation of a binary tree of letters:
A leaf in a binary tree is a node whose subtrees are both empty. In the example in Figure 1, this would be the five nodes with data B, D, H, P, and Y.
The preorder traversal of a tree of letters satisfies the defining properties:
The preorder traversal of the tree in Figure 1 is KGCBDHQMPY.
A tree like the one in Figure 1 is also a binary search tree of letters. A binary search tree of letters is a binary tree of letters in which each node satisfies:
The problem:
Consider the following sequence of operations on a binary search tree of letters
Remove the leaves and list the data removed
Repeat this procedure until the tree is empty
Starting from the tree below on the left, we produce the sequence of trees shown, and then the empty tree
by removing the leaves with data
BDHPY
CM
GQ
K
Your problem is to start with such a sequence of lines of leaves from a binary search tree of letters and output the preorder traversal of the tree.
The input file will contain one or more data sets. Each data set is a sequence of one or more lines of capital letters. The lines contain the leaves removed from a binary search tree in the stages described above. The letters on a line will be listed in increasing alphabetical order. Data sets are separated by a line containing only an asterisk ('*'). The last data set is followed by a line containing only a dollar sign ('$'). There are no blanks or empty lines in the input.
For each input data set, there is a unique binary search tree that would produce the sequence of leaves. The output is a line containing only the preorder traversal of that tree, with no blanks.
BDHPY CM GQ K * AC B $
KGCBDHQMPY BAC______________________________________________________ 2065false
IONU Satellite Imaging, Inc. records and stores very large images using run
length encoding. You are to write a program that reads a compressed image, finds
the edges in the image, as described below, and outputs another compressed image
of the detected edges.
A simple edge detection algorithm sets an output pixel's value to be the maximum
absolute value of the differences between it and all its surrounding pixels in
the input image. Consider the input image below:
The upper left pixel in the output image is the maximum of the values 1515, 15100, and 15100, which is 85. The pixel in the 4th row, 2nd column is computed as the maximum of 175100, 175100, 175100, 175175, 17525, 175175, 175175, and 17525, which is 150.
Images contain 2 to 1,000,000,000 (10^{9}) pixels. All images are encoded using run length encoding (RLE). This is a sequence of pairs, containing pixel value (0255) and run length (110^{9}). Input images have at most 1,000 of these pairs. Successive pairs have different pixel values. All lines in an image contain the same number of pixels.
Input consists of information for one or more images. Each image starts with
the width, in pixels, of each image line. This is followed by the RLE pairs, one
pair per line. A line with 0 0 indicates the end of the data for that image. An
image width of 0 indicates there are no more images to process. The first image
in the example input encodes the 5x7 input image above.
7 15 4 100 15 25 2 175 2 25 5 175 2 25 5 0 0 10 35 500000000 200 500000000 0 0 3 255 1 10 1 255 2 10 1 255 2 10 1 255 1 0 0 0
7 85 5 0 2 85 5 75 10 150 2 75 3 0 2 150 2 0 4 0 0 10 0 499999990 165 20 0 499999990 0 0 3 245 9 0 0 0______________________________________________________ 2066false
Instruens Fabulam means drawing a chart (or table) in Latin. That's what you will do for this problem..
The input consists of one or more table descriptions, followed by a line whose first character is '*', which signals the end of the file. Each description begins with a header line containing one or more characters that define the number and alignment of columns in the table. Each character in the header line is either '<', '=', or '>', and indicates a leftjustified, centered, or rightjustified column. Following the header are at least two and at most 21 data lines that contain the entries for each row. Each data line consists of one or more nonempty entries separated by an ampersand ('&'), where the number of entries is equal to the number of columns defined in the header line. The first data line contains entries for the column titles, and the remaining data lines contain entries for the body of the table. Spaces may appear within an entry, but never at the beginning or end of an entry. The characters '<', '=', '>', '&', and '*' will not appear in the input except where indicated above.
For each table description, output the table using the exact format shown in the examples. Note that
Input and correct output files satisfy all the requirements listed in Notes to Teams, except that the output may contain two or more consecutive spaces. There are no spaces at the beginning or end of lines, and only spaces are used (never tabs).
<>=> TITLE&VERSION&OPERATING SYSTEM&PRICE Slug Farm&2.0&FreeBSD&49.99 Figs of Doom&1.7&Linux&9.98 Smiley Goes to Happy Town&11.0&Windows&129.25 Wheelbarrow Motocross&1.0&BeOS&34.97 > What is the answer? 42 <> Tweedledum&Tweedledee "Knock, knock."&"Who's there?" "Boo."&"Boo who?" "Don't cry, it's only me."&(groan) *
@@  TITLE  VERSION  OPERATING SYSTEM  PRICE  +++  Slug Farm  2.0  FreeBSD  49.99   Figs of Doom  1.7  Linux  9.98   Smiley Goes to Happy Town  11.0  Windows  129.25   Wheelbarrow Motocross  1.0  BeOS  34.97  @@ @@  What is the answer?    42  @@ @@  Tweedledum  Tweedledee  +  "Knock, knock."  "Who's there?"   "Boo."  "Boo who?"   "Don't cry, it's only me."  (groan)  @@______________________________________________________ 2067false
Given cells filled with functional formulas and data, display the calculated results of a minispreadsheet. Spreadsheet cells are labeled by columns(AJ) and rows (110). The cell in the 6th column of the 3rd row would be labeled with address F3. All cell entries will be integers. All function names and cell references are case insensitive. Any function not adhering to proper syntax should output `#SYN#' in its cell. The functions the spreadsheet should handle are as follows:
k may be a cell address. Ex.. Large(2,2,5,5,5,8,8,8,3) is 2.
Output `#ERR#' if impossible. Ex.. Large(2,2,5,5,5,8,8,4)
Ex. CountIF(A4, B1:B5, ``>0")
The median is the middle number of the cells if they are in numerical order. If the Range contains an odd number of cells, the median is the average of the two middle cells. Truncate the result if there is an even number of cells.
The mode is the most frequently occurring value in the range. In case of a tie, use the first modal value occurring in a list of the Range values. Rectangular sections of the Range should be listed by rows, from left to right.
If a cell in the Evaluation Range meets the specified condition, the corresponding cell in the Sum Range should be included in the sum. Output `#ERR#' if there is not a 11 correspondence between Evaluation Range cells and Sum Range cells. Condition specifications are the same as those of the CountIf function. Rectangular sections of the Range are in row major form. That is, they should be listed by rows, from left to right. Any blank cell in the Evaluation Range counts for purposes of the required 11 correspondence, but the condition should automatically evaluate to False.
Ex. If A1=1, A2=2, A4=4, B1=10, C1=20,B3=30, B4=40
SumIf(A1:A2, 3 ,A4, ">2" , B1 , C1 ,B3:B4) is 70.
A range may be a < Cell Address >, < Cell Address : Cell Address >, any integer, or a combination of these separated by commas.
Examples are `C5', or `A3:B4' (meaning A3,B3,A4, and B4), `55', or the combination `D2, 55, A3:B4, J3', respectively. There may be spaces within the parentheses. There will not be spaces separating a column and a row in a cell address.
Input beginning with `R' indicates a particular row's data. Any row not accounted for should be filled with blanks. If a row is listed, all entries in the row are listed, from left to right, separated by blank(s). A row's entries may extend over more than one line.
There are no circular references in the data; however, one cell's function may use another cell's results as input. If there is an `#ERR#' or `#SYN#' in an input cell the function should display `#INP#'. If there is an `#INP#' in any input cell the function should display `#INP#'. `#INP#' is the error with most precedence.
R1 8 4 5 7 B 4 3 6 90 B R3 7 8 11 14 Average(A3:D3,A3) SumF(A1 A2) B B B B R5 B 3 4 B B B B B B Large( B1:B10 , 3) R6 B 4 3 B B B B B B Average(4, J7) R7 B CountIf(B1:B6,">0") LARGE(C1:C6,D1:E6,1) B B B B B B Large(B1:B10, 5) R10 B Mode(A1:I1) Median(A1:I1,B1:B3) B B B B B B SUMIF(B5:C6,">3",A1:D1)
A B C D E F G H I J 1 8 4 5 7 4 3 6 90 2 3 7 8 11 14 9#SYN# 4 5 3 4 3 6 4 3 #INP# 7 4 14 #ERR# 8 9 10 4 5 9______________________________________________________ 2068false
PC^{}3 is intended as a postprocessor for PC^{}2, which is popular with ACMers, to allow for an alternative way of scoring to be used for our local contest. After a local guru has written a script for extracting necessary information from the PC^{}2 databases in the following format:
Your task is to write a program to use the data extracted from the PC^{}2 database and declare the winner, or winners.
Input to this problem consists of a sequence of one or more contests. Each contest is described by several lines as follows:
The input will be terminated by a line that consists of four zeros (0 0 0 0), separated by a single space. This line should not be processed.
For each contest, the output is one line that contains the contest label and numbers of the winning team numbers (sorted in increasing order) as shown in the Sample Output below.
1 5 20 6 3 3 10 30 100 6 1 16024555 0 3 2 15895629 4 3 2 765629 0 17 4 1120132 0 3 2 1895629 3 6 3 9024555 0 2 5 20 7 3 10 10 30 100 6 1 16024555 0 3 2 15895629 5 3 2 765629 0 17 4 1120139 0 5 4 1895629 0 6 3 9024555 0 10 4 2895629 0 0 0 0 0
Contest 1 Winner: Team 17 Contest 2 Winner: Team 5 and Team 10 and Team 17
______________________________________________________ 2069false
A group of ACMers designed a variation, and a much simpler one at that, of the popular game TARGET to help them relax while waiting for the judges' declaration of the final scores. The game consists of finding words that satisfy certain criterion (e.g., start with ``dog" (``dogma") or contain ``cat" (``scatological"), used in the news today (``nuclear"), etc).
For this game the group agreed that longer words are more worthy than short words and unusual words are better than common words, where commonness is defined as the number of participants who all think of the same word. The score for a word is calculated as its number of letters divided by the number of participants choosing it. Examples are: the word ``direkt" chosen by a single German participant scores ``6" points for her, and the word ``directly" chosen by three participants scores only ``8/3" for each of them.
The total score for each participant is the sum of his/her individual word scores. The group has also set some rules for the game:
Your task is to write a program that processes several lists of words, one for each participant, and determines the winner. You do not have to worry about checking the validity of the words against the criterion. The participants will perform this task as part of learning new and foreign words.
Input for this problem consists of a sequence of one or more rounds of the game. Each round is described by several lines as follows:
For each round, the output consists of two lines. The first line contains the round number starting with 1 as shown in the Sample Output below. The second line contains the names of participants with the highest score in this round, separated by a single space. The names must appear in the same order as they appear in the input.
4 John dire direct direction Jane direkt Joan direction Janet vondire direction 2 john great admired politician Kim great loss poorer 2 peter moral choice paul moral choice 0
Round 1 John Round 2 john Round 3 peter paul
______________________________________________________ 2070false
Chip and Dale have devised an encryption method to hide their messages. They first agree secretly on a number that will be used as the number of columns in a matrix. The sender prepares an intermediate format by removing capitalizations and punctuations and spaces from the message. The sender then enters the letters of the intermediate format along the diagonals of the matrix and pads with extra random letters so as to make a rectangular array of letters. For example, if the message is ``There's no place like my office on a muggy day" and there are five columns, Dale would write down
Note how Dale includes only the letters and writes them all in lower case. Dale then sends the message to Chip by writing the letters in each row. So, the message in its intermediate format would be encrypted as
In this example, Dale used the character `x' to pad the message out to make a rectangle, although he could have used any letter.
Your job is to recover for Chip the message in its intermediate format from the encrypted one.
There will be multiple input sets. Input for each set will consist of two lines. The first line will contain an integer in the range 2...20 indicating the number of columns used. The next line is a string of up to 200 lower case letters. The last input set is followed by a line containing a single zero (0). This line should not be processed.
Each input set should generate one line of output, giving the message in its intermediate format followed by the padding letters.
5 thrnaeeockspeefllmfoiyingocagaemyyxudxxx 3 thsiiesaysxx 0
theresnoplacelikemyofficeonamuggydayxxxx thisiseasyxx
______________________________________________________ 2071false
The manager of a packing warehouse, which specialises in packing breakable items, contracted a supplier for boxes of sizes from the Fibonacci sequence. I am not sure of the reason behind it, but it is rumoured to be related to the recent ``Da Vinci code" movie. An item whose size is in the sequence can be packed in a box of equal size with no filling, but an item whose size is not in the sequence must be packed with sufficient filling material to fill the box and protect the item from breaking. An item cannot be split between two boxes, and each item must be packed separately in its own box.
The second twist in this story, which makes it the more bizarre, is that the company only receives a daily filling material delivery of size F to be used. At the end of each day, any unused filling material is discarded.
Your task is to maximize the number of items shipped each day for a given amount of filling material F and a given list of items.
Input to this problem consists of packing tasks for one or more days. The tasks for each day are described by two lines as follows:
The input will be terminated by a line that consists of three zeros (0 0 0), separated by a single space. This line should not be processed.
For each day, the output consists of one line that contains the number of items that can be packed for that day.
4 10 30 7 15 30 5 11 100 5812167 20 40 30 15 17 5812167 23 43 33 13 37 0 0 0
3 10
______________________________________________________ 2072false
The reading of ``Flatland: A Romance of Many Dimensions" by Edwin Abbott had a profound, and rather unusual, effect on young Bob and his mother too. Bob started to only use things that are either flat or with flat sides: Soup bowls, dishes, glasses, mugs, and even the cutlery. However the annoying part, for his mother that is, was the way he reorganized the cupboard. Bob removed all the shelves and drew a grid, with integer coordinates, (0 0) for the lower left corner and (1000 1000) for the upper right corner, on the back of the cupboard. Bob will always stack the crockery neatly on top of each other. Neatly means aligned with his grid, so that he can record the location of each item by four integers that describe the coordinates of its lower left corner and its upper right corner. For the example, the red mug (labelled with Zs) is described by the four integers (1 0 3 3).
Bob's mother will not move a crockery item unless no other item in the cupboard exists vertically above it. This way she can be sure that none of Bob's precious mugs/glasses gets broken. Examples are: taking the yellow mug (labelled with Xs) requires her to move the grey ``rectangular" soup bowl (labelled with Ss) first, and taking the grey mug (labelled with Ys) requires her to move four items first.
Your task is to write a program to calculate for Bob's mother the number of items she must move before she can remove the item of her choice.
Input to this problem consists of a sequence of one or more situations. Several lines describe each situation as follows:
The input will be terminated by a line that consists of a zero (0). This line should not be processed.
For each situation, the output is a single line that contains the number of objects to be removed before the desired item can be removed in accordance with Bob's mother desires.
5 0 0 4 4 3 4 6 6 5 0 7 4 4 6 5 8 20 0 21 21 20 0 21 21 4 0 0 4 4 3 4 6 6 5 0 7 4 4 6 5 8 0 0 4 4 0
0 2
______________________________________________________ 2073false
A printed circuit board has a number of horizontal and vertical tracks that may be used to connect electronic components. The example below demonstrates a square board with 10 vertical tracks that we shall assign labels from 0 to 9 starting from the left end, 10 horizontal tracks that we shall assign labels from 0 to 9 starting from the bottom end, and 8 laid down wires (shown in black). Each wire occupies a single horizontal or a single vertical track, and is described by its lower left coordinate followed by its upper right coordinate. In the example below, the 8 wires are described by
A horizontal wire may overlap with a vertical wire in a single grid point. A horizontal wire may not overlap with another horizontal wire, except at their endpoints. Similarly a vertical wire may not overlap with another vertical wire, except at their endpoints.
Your task is to write a program to identify a path on a printed circuit board to connect two given points on the grid, which adheres to the above rules, such that the number of points your path has in common with the existing wires is minimised. The four red wires, in the above example, connect the points (6 8) and (5 1) with minimum number of 1 overlap. The green wires connect the same two points with 2 overlaps.
In some cases a path may not exist, but your program will only be used to connect a pair of points in printed circuit boards where such a path is known to exist. Those cases will be identified and removed by a sophisticated imaging system, but that is another story.
Input to this problem consists of a sequence of one or more design situations. Several lines describe each design situation as follows:
The input will be terminated by a line that consists of two zeros (0 0). This line should not be processed.
For each design situation, the output is a single line that contains the minimum number of overlaps.
8 10 0 0 1 0 4 0 4 6 0 5 5 5 8 2 8 6 6 4 6 7 7 6 7 8 2 6 5 6 7 8 9 8 6 8 5 1 7 10 0 0 1 0 4 0 4 6 0 5 5 5 8 2 8 6 6 4 6 7 2 6 5 6 6 4 8 4 6 8 5 1 0 0
1 0
______________________________________________________ 2074false
The Sudoku craze is sweeping the world, and that has got the ``Word Find" problem preparation company worried. The company wants to head off their losses in the market place by introducing a variation of the old game. This example, with 5 words and table size 8, is a typical second generation word find puzzle:
P  E  N  C  I  L  T  Y  CLASS 
C  O  K  L  B  O  O  K  ROCK 
Q  L  P  A  P  E  R  I  BOOK 
U  B  A  S  G  K  R  B  PENCIL 
E  E  P  S  C  N  O  U  PAPER 
E  A  E  O  S  O  C  R  
N  O  R  B  K  N  K  O  
J  R  X  R  Y  G  O  N 
Each of the given words may appear multiple times in the table more but no more than four (4) times. Each word may be oriented in any of the 8 possible directions. The aim is to locate the given words, which will be different to each other, with the added challenge that no two words may share a letter. A generated puzzle is ``soluble" if all the words can be found with no two words sharing a letter, and ``challenging" if at least one pair of the given words shares a letter in the table.
For the sake of saving development cost and reducing timetomarket, the company decided to use a tweaked version of their software to create the new puzzles and then reject those that are not suitable. Your task is to write a program to test the generated puzzles and to accept the ones that are both ``challenging" and ``soluble" and to reject all other puzzles. For the above example, your program should accept the generated puzzle and report ``YES" for being ``challenging" and ``YES" for being ``soluble".
Input to this problem consists of a sequence of one or more puzzles. Each puzzle is described by several lines as follows:
The input will be terminated by a line that consists of two zeros (0 0), separated by a single space. This line should not be processed.
For each puzzle, the output consists of two lines. The first line contains the puzzle number starting with the value of one (1), followed by a ``:`` and followed by `ACCEPT' or `REJECT' as shown in the Sample Output below. The second line contains `YES' if the puzzle is challenging and `NO' otherwise, followed by a single space, and followed by `YES' if soluble and `NO' otherwise.
3 4 PEN NET PET P E N S O N E T P E T K S P E N 2 3 NO OR O R M X R Y T N O 2 2 NO OR N O X R 0 0
Puzzle 1: ACCEPT YES YES Puzzle 2: ACCEPT YES YES Puzzle 3: REJECT YES NO
______________________________________________________ 2075false
Chairlift 
A chairlift is used to transport skiers (or summer sightseers) up the mountain. Figure 1 shows the components of a chairlift, viewed from the air above the chairlift:
Here is a formatting template shown between two lines of the above output:
1234567890123456789012345678901234567890123456789 N = 126, T = 225.0 Chair 56 meets chair 71, remaining time = 198.9
Note in particular, that:
all numerical values are rightjustified in the output fields shown by the formatting template. floating point values (representing seconds) will be displayed with one digit following the decimal point.
126 225.0 56 71 31 120 100 53
Program 1 by team X N = 126, T = 225.0 Chair 56 meets chair 71, remaining time = 198.9 Chair 31 meets chair 120, remaining time = 65.7 Chair 100 meets chair 53, remaining time = 83.7 End of program 1 by team X
Reserve Bookshelf 
A very small rural library has only one shelf dedicated to reserve books (reserve books are deemed important to a large number of library users and can therefore be checked out only for very short periods of time) .
When the library's staff places a book on reserve, the book is put on the reserve shelf's left end. All books that were already on the reserve shelf must therefore be moved to the right, just enough to make room for the new book on the shelf. When a reserve book is checked out and subsequently returned, it is also put on the reserve shelf's left end, as if it were just being placed on reserve. What happens when the shelf is full? When a book is placed on reserve, or when a previously checked out reserve book is returned, and there is not enough room on the reserve bookshelf, then, starting at the right end, as many books (but no more) are removed from the reserve shelf (they are "taken off reserve") as needed in order to make room for the book to be put on the reserve bookshelf.
Each subsequent line of input will start with one of the four commands ADD, CHECKOUT, RETURN, PRINT in upper case letters, starting in column 1.
The ADD command is followed by a title (starting in column 10), consisting of at most 29 printable characters. The title is followed (starting in column 40) by the thickness of the book (the amount of book shelf space it will require), a positive integer, not greater than 150. The effect of the ADD command will be to place a new title on reserve, as described above. Once a particular title has been ADDed, it will not be ADDed again as long as that book is on the reserve book shelf or has been checked out. However, if a title has been forced off the reserve book shelf (by another ADD command or by a RETURN command) then that title may appear in a subsequent ADD command (with the same thickness as before). The CHECKOUT command is followed by a title (starting in column 10) which is currently on the reserve shelf. The effect of the CHECKOUT command is to remove the specified title from the reserve shelf (until it is placed back on the reserve shelf by a subsequent RETURN command. A CHECKOUT may create a gap between two books (for example, when "The C Programming Language" is checked out in the example shown). Such a gap will count as part of the free space. The RETURN command is followed by a title (starting in column 10) which is currently checked out. The effect of the RETURN command is to put the specified book to the left end of the reserve shelf, as described in the introductory paragraphs. The effect of the PRINT command will be to display in the output file: the title and thickness of each book currently on the reserve shelf, one book per line, in the (lefttoright) order in which the books are currently on the reserve shelf, the currently available space on the reserve shelf, and one blank line.
There will not be any trailing blank spaces in the input file.
250 PRINT ADD 101 Uses for a Dead Cat 38 ADD Thin Thighs in 30 Days 63 ADD The Republic 44 ADD Mein Kampf 101 PRINT ADD Principia Mathematica 79 PRINT CHECKOUT The Republic ADD On the Origin of Species 55 ADD The C Programming Language 15 PRINT RETURN The Republic ADD 101 Uses for a Dead Cat 38 CHECKOUT The C Programming Language PRINT
Program 2 by team X AVAILABLE SHELF SPACE: 250 Mein Kampf 101 The Republic 44 Thin Thighs in 30 Days 63 101 Uses for a Dead Cat 38 AVAILABLE SHELF SPACE: 4 Principia Mathematica 79 Mein Kampf 101 The Republic 44 AVAILABLE SHELF SPACE: 26 The C Programming Language 15 On the Origin of Species 55 Principia Mathematica 79 Mein Kampf 101 AVAILABLE SHELF SPACE: 0 101 Uses for a Dead Cat 38 The Republic 44 On the Origin of Species 55 Principia Mathematica 79 AVAILABLE SHELF SPACE: 34 End of program 2 by team X
Clock 
You are given a standard 12hour clock with analog display, an hour hand and a minute hand. How many times does the minute hand pass the hour hand in a given time interval?
Here is a formatting template shown between two lines of the above output:
Initial time Final time Passes 12345678901234567890123456789012 12:50 01:02 0
12 50 1 2 3 8 3 20 2 45 11 0 11 0 3 20 1 2 12 50 3 20 3 8
Program 3 by team X Initial time Final time Passes 12:50 01:02 0 03:08 03:20 1 02:45 11:00 8 11:00 03:20 4 01:02 12:50 11 03:20 03:08 10 End of program 3 by team X
Given a triangle, you're asked to find the points with integer coordinates in its interior.
Figure 1 illustrates the first triangle of the sample input, and the points with integer coordinates in its interior. Note that (1,3) lies on this triangle's border and is therefore not encapsulated by the triangle.
Each triangle specified in the input will encapsulate at least one point with integer coordinates. Within each line of input, the difference between the largest and smallest xcoordinate will not exceed 9.
Points (x, y) which are listed on one line of output have the same ycoordinate; the xcoordinates of these points are in increasing order from left to right. The ycoordinates of points in the interior of a triangle will be in decreasing order from one line of output to the next line.
Each (x, y) point will be printed in a ninecolumn output field. Points that have the same xcoordinate (and pertain to the same triangle) will be listed in the same ninecolumn output field. Here is a formatting template between two lines of the above output:
( 2, 3) ( 3, 3) 12345678901234567890123456789012345678901234567890 (1, 2) ( 0, 2) ( 1, 2) ( 2, 2) ( 3, 2)
Each ninecolumn output field has the following layout (unless it is blank):
Column 1: opening parenthesis Columns 23 : x coordinate (right justified) Column 4: comma Columns 57 : ycoordinate (right justified) Column 8 : closing parenthesis. Column 9: blank space to separate current ninecolumn field from the next one, if there is a next one.
The line(s) containing the smallest xvalue pertaining to a particular triangle (such as 1 for the first triangle in the above example) will not start with a blank output field. There will not be a blank output field between two nonblank ones on a given line. After listing the points encapsulated by each triangle, your program will produce one blank line of output. There will not be any additional blank lines in the output.
4 4 2 1 2 2 2 4 4 3 0 1
Program 4 by team X ( 2, 3) ( 3, 3) (1, 2) ( 0, 2) ( 1, 2) ( 2, 2) ( 3, 2) ( 0, 1) ( 1, 1) ( 2, 1) ( 1, 0) ( 2, 0) ( 2, 3) ( 2, 2) ( 1, 1) ( 2, 1) ( 1, 0) ( 2, 0) ( 3, 0) ( 1, 1) ( 2, 1) ( 3, 1) ( 3, 2) End of program 4 by team X
______________________________________________________ 2079false
The Zhombi tribe populates an island in the South Pacific. The tribe consists of a number of clans (which are collections of related families). The tribe has a chief, and so does each clan.
When a tribal law is proposed, the voting members of each clan convene and vote on the proposal. In case of a tie, the clan chief (who is otherwise not a voting member) will break the tie.
After the clans have voted, the clan chiefs convene at the tribal headquarters to conduct the tribal level vote, which will determine whether the proposal passes. There each clan chief will cast a number of votes equal to the number of voting members of his/her tribe. Furthermore, all votes cast by one clan chief will be either in favor of the proposal or against the proposal, depending on how his/her clan voted. For example, if clan A has 28 voting members and voted in favor of the proposal, then clan A's chief will cast all 28 votes in favor of the proposal at the tribal level, even if the vote at the clan level was "15 for 13 against", or if the vote at the clan level was a 14:14 tie that the clan chief chose to break in favor of the proposal. In case of a tie at the tribal level vote, the tribal chief (who is otherwise not a voting member) will break the tie.
You probably suspect now that a proposal could pass at the tribal level even if fewer than 50% of all votes were cast in its favor at the clan level. The main goal of the program will be to determine the smallest number of clanlevel votes needed to pass a law at the tribal level, without having to break a tie either at the clan level or at the tribal level.
Each number in the input file represents the number of voting members of a clan (not counting the chief). We will refer to the clans of the tribe by upper case letters, in alphabetical order. Thus, the data in this example specify that the tribe consists of four clans, A, B, C, and D, having 28, 12, 15, and 7 voting members, respectively.
The line labeled "Clan" lists (in increasing alphabetical order) those clans that voted in favor of the proposal. The line labeled "Clan level votes" lists the (smallest) number of clanlevel votes needed from each clan that voted in favor of the proposal, in order to pass the proposal at the tribal level. In those clans that are not listed, all votes were cast against the proposal. The line labeled "Tribal level votes" lists the votes cast in favor of the proposal at the tribal level.
In the two "summary" lines:
The number 19 represents the crux of the results, it is the smallest number of clanlevel votes which can result in the stated goal. The total (62 in this case) will always be the same number on the two "summary" lines; it is simply the sum of the numbers in the input. The percentage of triballevel votes (56.5% in this case) will always be greater than 50% (in some cases the output, rounded to one decimal place, may be 50.0% even though the actual percentage is greater than 50%).
There could be several correct instances. In particular, for a given input, all correct instances of output will be identical on the line "Clan level summary". Other lines of the output may be different, as long as the conditions of the problem are met.
Pay attention to all formatting details, such as the presence or absence of blanks lines, blank spaces, punctuation, upper/lower case letters. The letters and numbers displayed on the "Clan", "Clan level votes", and "Tribal level votes" lines are rightjustified in fields of width 4. Integer values that appear in the "summary" lines are rightjustified in fields of width 6. You may assume that no more than 14 clans voted in favor of the proposal.
Here is a formatting template shown between two lines of the second instance of output from above:
Tribal level votes: 12 15 7 12345678901234567890123456789012345678901234567890 Clan level summary: 19 out of 62, 30.6%
Note the column numbers of the '9' in 19, the comma, the decimal point, and the percent sign. The percentages are displayed to a precision of one digit after the decimal point.
Print a blank line between consecutive test cases.
28 12 15 7
Program 5 by team X Clan: A D Clan level votes: 15 4 Tribal level votes: 28 7 Clan level summary: 19 out of 62, 30.6% Tribal level summary: 35 out of 62, 56.5% End of program 5 by team X
Nonuniqueness of output:
For the specific input shown above, the output shown above is not the only correct output. Here is another instance of correct output for the input shown above:
Program 5 by team X Clan: B C D Clan level votes: 7 8 4 Tribal level votes: 12 15 7 Clan level summary: 19 out of 62, 30.6% Tribal level summary: 34 out of 62, 54.8% End of program 5 by team X
______________________________________________________ 2080false
Floating point numbers are represented at the hardware level of most computer systems in normalized binary scientific notation. We will consider a hypothetical computer in which floating point numbers are represented in a 16bit word. An example is shown in Figure 1:
The period preceding the mantissa is the "binary point" which has the same meaning as the decimal point in a decimal (base ten) representation. In the normalized binary scientific notation there is only one binary digit preceding the binary point, and it is always 1 (except if the floating point number is the number zero). It is called the characteristic. Since it is always 1, it does not explicitly appear in the 16bit representation of Figure 1.
Since the number 1.01001100 is in binary, the digits to the right of the binary point represent successive negative powers of 2. Therefore, the number shown in Figure 2 can be rewritten as:
The following formatting conventions are required in your output:
The floating point numbers will be displayed in scientific notation (base ten). Column 1 will either be blank (indicating a positive number or zero) or contain a minus sign (indicating a negative number). Column 2 will contain a digit. Column 3 will contain the decimal point. Columns 4  9 will contain six additional significant digits of the floating point number. The remaining columns will specify the exponent of scientific notation. The sign and magnitude of the exponent must of course be correct, but the exact format in which the exponent is displayed will be determined by the programming language you use.
1100001001001100 0011111100000000 1011111110000000 0000000010101010 0011011111100000 1001111011100000 0101011001010101 0100011011101101 0111111111111111 1100001000101100 0000000000000000 1000000000000000
Program 6 by team X 1.037500e+001 1.000000e+000 1.500000e+000 1.804180e019 7.324219e003 2.182787e010 1.117389e+007 2.465000e+002 3.682143e+019 9.375000e+000 0.000000e+000 0.000000e+000 End of program 6 by team X
______________________________________________________ 2081false
Bioinformatics is an exciting new field of science, in which computer science techniques are applied to solving biological problems. The search for genetic drugs is one of the central problems of bioinformatics. In tackling this problem, genes from various organisms are compared.
A gene is characterized by the sequence of amino acids that can be derived from it. There are altogether 20 amino acids. Each amino acid is identified by a oneletter abbreviation of its full chemical name (the upper case letters of the alphabet, except B, J, O, U, X, and Z, are used to identify amino acids).
Your program will look for discrepancies among the amino acid sequences of the given organisms.
The first line specifies the names of the organisms. Each name consists of at least one but not more than eight lower case characters and is rightjustified in a field of width 9 characters.
Each of the remaining lines specifies an amino acid for each of the organisms listed on the first line. Each amino acid is represented by its oneletter abbreviation, rightjustified in a field of width 9 characters, under the name of the organism with which it is associated. Thus, in the example shown, the amino acid sequence for the particular yeast gene is M, E, S, L, D, A, N, C, T, M.
The amino acid sequences of all organisms represented in a given input file will have the same length (in this example, 10). The minimum length of the amino acid sequences in the input file is 10, the maximum length is 9999.
Each amino acid in the amino acid sequence of a particular gene occupies a certain position. The positions are numbered starting at 1 and they increase sequentially. Thus, the yeast sequence in the example shown has M in positions 1 and 10, E in position 2, A in position 6, etc.
In those positions in which not all organisms have the same amino acid (positions 3, 4 ,7, 8 and 10 in the example shown) your program will:
Print the position number. Identify by an asterisk those organisms that deviate (in that particular position) from the most frequently occurring amino acid (in that particular position). In position 3 of the given example, S is certainly the most frequently occurring amino acid, and human is the only organism that does not have S in position 3. In case of a tie for the most frequently occurring amino acid in a particualar position, the amino acid that as the rightmost occurrence (among those involved in the tie) will be chosen as the most frequent one. For example, in position 8 in the given example, both C and A occur twice. We choose C as the most frequent amino acid in position 8, because its rightmost occurrence is under yeast, which is further right than the rightmost occurrence of A (nematode) in this position. In the given example, there is an extreme case of a tie in position 10: all five organisms have different amino acids. Therefore, the amino having the rightmost occurrence, namely R, will be designated as the most frequent one.
Two lines of the above output are reproduced here with a formatting template:
1 2 3 4 5 6 7 12345678901234567890123456789012345678901234567890123456789012345678901234567890 human fruitfly nematode yeast bacteria 3 *
Note in particular:
The position numbers are right justified in columns 14. Column 5 is blank. Starting in column 6, the output (name of an organism or an asterisk) will be rightjustified in fields of width 9.
Also pay attention to formatting details, such as upper/lower case variations, blank spaces, and the absence of blank lines.
human fruitfly nematode yeast bacteria M M M M M E E E E E C S S S S L L L L W D D D D D A A A A A K Q G N G C A A C K T T T T T S H E M R
Program 7 by team X human fruitfly nematode yeast bacteria 3 * 4 * 7 * * * 8 * * * 10 * * * * End of program 7 by team X
______________________________________________________ 2082false
This program will acquaint you with the judicious method used by rulers of the ancient Roman empire to choose the locations of their military forts.
You are given a collection of cities. The cities will be labeled by upper case letters in alphabetical order, starting with 'A'. Given any pair of cities, there is one and only one path between them (see Figure 1).
The total number of cities in the given collection. It will be in the range 3..26. In this example, it is 11, which means that the cities are labeled A..K. An upper case letter in the valid range of cities, denoting the city which is initially fortified. The total number of cities that are to be fortified, including the initially fortified one. It will be at least three and not greater than the total number of cities in the collection
Each of the remaining lines of the input file will contain two upper case letters, separated by one or more blank spaces. Each letter will be in the range of labels of cities in the given collection. Each pair of letters on one line of input determines a direct connection between two cities. The direct connections listed in the sample input is identical to the direct connections of Figure 1. The set of direct connections listed in the input will satisfy all previously stated conditions.
All lines of input will be free of leading or trailing blank spaces.
The upper case letters denoting the cities in the output will be separated by one blank space. There will not be any blank lines or leading blank spaces in the output.
11 J 5 A D B E F B C G F G C A G H G I J C K F
Program 8 by team X J E D H K End of program 8 by team X
Explanation of the sample output:
When there is only one fortified city, the degree of vulnerability of each vulnerable city is its distance from the fortified city. Initially, with J being the only fortified city, E is the most vulnerable city with degree of vulnerability 5.
With J and E being fortified, D, H, I, and K contend for being the most vulnerable city, all having degree of vulnerability 3. For example, the distance from D to E is 6, the distance from D to J is 3; the smaller of these two numbers is 3. Therefore, the degree of vulnerability of D is 3. The alphabetically first city among the four contenders (D, H, I, and K) is D, which will be the next city to be fortified.
Similarly, H, and then K, will be selected as the next city to be fortified. At this point, the number of fortified cities is 5 (as specified in the input), and the program terminates. Note that city I is not fortified, because its degree of vulnerability drops from 3 to 2 once H is fortified, making K the most vulnerable city.
______________________________________________________ 2083false
A simple mathematical formula for e is
where n is allowed to go to infinity. This can actually yield very accurate approximations of e using relatively small values of n.
There is no input file for this problem.
Output the approximations of e generated by the above formula for the values of n from 0 to 9. The beginning of your output should appear as in the sample output below.
There is no sample input for this problem.
n e   0 1 1 2 2 2.5 3 2.666666667 4 2.708333333______________________________________________________ 2084false
Imagine a perfectly formed honeycomb, spanning the infinite Cartesian plane. It is an interlocking grid composed of congruent equilateral hexagons. One hexagon is located so that its center is at the origin and has two corners on the Xaxis. A bee must be very careful about how it travels in order not to get lost in the infinite plane. To get from an arbitrary point A to another arbitrary point B, it will first head from A to the exact center of the hexagon in which A is located. Then, it will travel in a straight line to the exact center of an adjacent hexagon. It will move from center to adjacent center until it has reached the hexagon containing point B. At the destination hexagon, it will move from the center to point B. In all cases, the bee will take a path of minimal distance that obeys the rules. The figure below demonstrates one possible minimal path from point A to point B.
Input will be in the form of 5 floating point numbers per line. The first number will be the length, in centimeters, of the sides of the hexagons. The next two numbers will be the x and y coordinates of point A, followed by the x and y coordinates of point B. The input will be terminated by a line containing five zeroes. Neither point A nor point B will ever be exactly on a border between hexagons.
For each line of the input, output the minimum length of a path from point A to point B, to the nearest 0.001 centimeters.
1.0 3.2 2.2 3.3 0 9 1 4 5 1 0.1 0.09 0 0.21 0 0 0 0 0 0
7.737 5.000 0.526______________________________________________________ 2085false
The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.
For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now, consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yields 3, a single digit and also the digital root of 39.
The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of 0.
For each integer in the input, output its digital root on a separate line of the output.
24 39 0
6 3______________________________________________________ 2086false
In this problem, you will be given a series of lists containing both words and numbers. The goal is to sort these lists in such a way that all words are in alphabetical order and all numbers are in numerical order. Furthermore, if the n^{th} element in the list is a number, it must remain a number, and if it is a word, it must remain a word.
The input will contain multiple lists, one per line. Each element of the list will be specified by a comma followed by a space, and the list will be terminated by a period. Words will contain only letters (and no two words will be duplicated), while numbers will contain only digits and the optional plus or minus sign at the very beginning and will fit into a 32bit signed integer. The input will be terminated by a line containing a single period.
For each list in the input, output the scramble sorted list, separating each element of the list with a comma followed by a space, and ending the list with a period.
0. banana, strawberry, OrAnGe. Banana, StRaWbErRy, orange. 10, 8, 6, 4, 2, 0. x, 30, 20, z, 1000, 1, Y. 50, 7, kitten, puppy, 2, orangutan, 52, 100, bird, worm, 7, beetle. .
0. banana, OrAnGe, strawberry. Banana, orange, StRaWbErRy. 0, 2, 4, 6, 8, 10. x, 20, 1, Y, 30, 1000, z. 100, 2, beetle, bird, 7, kitten, 7, 50, orangutan, puppy, 52, worm.______________________________________________________ 2087false
XML, eXtensible Markup Language, is poised to become the lingua franca of structured data communication for the foreseeable future, due in part to its strict formatiing requirements. XML parsers must report anything that violates the rules of a wellformed XML document. An XML document is said to be wellformed if it meets all the wellformedness constraints as defined by the World Wide Web Consortium (W3C) XML specification.
XML documents are composed of units called elements, that contain either character data and/or other elements. Elements may also contain within their declaration, values called attributes. Consider the following XML document:
<?xml version="1.0"?> <customer> <name> <first>John</first> <last>Doe</last> </name> <address> <street> <number>15</number> <direction>West</direction> <name>34th</name> </street> <city>New York</city> <statecode>NY</statecode> <zipcode format="PLUS4">100010001</zipcode> <countrycode>USA</countrycode> </address> <orders/> </customer>
The bold identifiers contained within angle brackets are the elements of the document. The italicized identifer "format" within the "zipcode" element is an attribute of that element. All elements, with the exception of "orders", have a start and an end declaration, also called tags. The "orders" element is an empty element, as indicated by the "/>" sequence that closes the element, and does not require a separate endtag. The first line is a processing instruction for an XML parser and is not considered an element of the document.
The rules for a wellformed document are:
The input will contain a series of XML documents. The start of each document is identified by a line containing only the processing instruction "<?xml version="1.0">". The end of the input is idenitified by a line containing only the text "<?end?>" (this is not a true XML processing instruction, just a sentinel used to mark the end of input for this problem). As with all XML documents, white space between elements and attributes should be ignored. You may make the following assumptions with regards to the input.
For each input XML document, output a line containing the text "wellformed" if the document is wellformed, and "non wellformed" otherwise.
<?xml version="1.0"> <acmcontestproblem> <title>A WellFormed Problem</title> <text>XML, eXtensible Markup Language, is poised to become the lingua franca of structured data communication for the foreseeable future. [...]</text> <input>probleme.in</input> <output>probleme.out</output> </acmcontestproblem> <?xml version="1.0"?> <shoppinglist> <items> <item quantity="1" quantity="1">Gallon of milk</item> <item>Frozen pizza </items> </Shoppinglist> <errandlist> <errand>Get some cash at the ATM <errand>Pick up dry cleaning</errand> </errand> </errandlist> <?end?>
wellformed non wellformed______________________________________________________ 2088false
An entropy encoder is a data encoding method that achieves lossless data compression by encoding a message with "wasted" or "extra" information removed. In other words, entropy encoding removes information that was not necessary in the first place to accurately encode the message. A high degree of entropy implies a message with a great deal of wasted information; English text encoded in ASCII is an example of a message type that has very high entropy. Already compressed messages, such as JPEG graphics or ZIP archives, have very little entropy and do not benefit from further attempts at entropy encoding.
English text encoded in ASCII has a high degree of entropy because all characters are encoded using the same number of bits, eight. It is a known fact that the letters E, L, N, R, S and T occur at a considerably higher frequency than do most other letters in English text. If a way could be found to encode just these letters with four bits, then the new encoding would be smaller, would contain all the original information, and would have less entropy. ASCII uses a fixed number of bits for a reason, however: it's easy, since one is always dealing with a fixed number of bits to represent each possible glyph or character. How would an encoding scheme that used four bits for the above letters be able to distinguish between the fourbit codes and eightbit codes? This seemingly difficult problem is solved using what is known as a "prefixfree variablelength" encoding.
In such an encoding, any number of bits can be used to represent any glyph, and glyphs not present in the message are simply not encoded. However, in order to be able to recover the information, no bit pattern that encodes a glyph is allowed to be the prefix of any other encoding bit pattern. This allows the encoded bitstream to be read bit by bit, and whenever a set of bits is encountered that represents a glyph, that glyph can be decoded. If the prefixfree constraint was not enforced, then such a decoding would be impossible.
Consider the text "AAAAABCD". Using ASCII, encoding this would require 64 bits. If, instead, we encode "A" with the bit pattern "00", "B" with "01", "C" with "10", and "D" with "11" then we can encode this text in only 16 bits; the resulting bit pattern would be "0000000000011011". This is still a fixedlength encoding, however; we're using two bits per glyph instead of eight. Since the glyph "A" occurs with greater frequency, could we do better by encoding it with fewer bits? In fact we can, but in order to maintain a prefixfree encoding, some of the other bit patterns will become longer than two bits. An optimal encoding is to encode "A" with "0", "B" with "10", "C" with "110", and "D" with "111". (This is clearly not the only optimal encoding, as it is obvious that the encodings for B, C and D could be interchanged freely for any given encoding without increasing the size of the final encoded message.) Using this encoding, the message encodes in only 13 bits to "0000010110111", a compression ratio of 4.9 to 1 (that is, each bit in the final encoded message represents as much information as did 4.9 bits in the original encoding). Read through this bit pattern from left to right and you'll see that the prefixfree encoding makes it simple to decode this into the original text even though the codes have varying bit lengths.
As a second example, consider the text "THE CAT IN THE HAT". In this text, the letter "T" and the space character both occur with the highest frequency, so they will clearly have the shortest encoding bit patterns in an optimal encoding. The letters "C", "I" and "N" only occur once, however, so they will have the longest codes. There are many possible sets of prefixfree variablelength bit patterns that would yield the optimal encoding, that is, that would allow the text to be encoded in the fewest number of bits. One such optimal encoding is to encode spaces with "00", "A" with "100", "C" with "1110", "E" with "1111", "H" with "110", "I" with "1010", "N" with "1011" and "T" with "01". The optimal encoding therefore requires only 51 bits compared to the 144 that would be necessary to encode the message with 8bit ASCII encoding, a compression ratio of 2.8 to 1.
The input file will contain a list of text strings, one per line. The text strings will consist only of uppercase alphanumeric characters and underscores (which are used in place of spaces). The end of the input will be signalled by a line containing only the word "END" as the text string. This line should not be processed.
For each text string in the input, output the length in bits of the 8bit ASCII encoding, the length in bits of an optimal prefixfree variablelength encoding, and the compression ratio accurate to one decimal point.
AAAAABCD THE_CAT_IN_THE_HAT END
64 13 4.9 144 51 2.8______________________________________________________ 2089false
An ntersection is defined as a location in ndimensional space, n being a positive integer, having all nonnegative integer coordinates. For example, the location (1,2,3) represents an ntersection in three dimensional space. Two ntersections are said to be adjacent if they have the same number of dimensions and their coordinates differ by exactly 1 in a single dimension only. For example, (1,2,3) is adjacent to (0,2,3), (2,2,3) and (1,2,4), but not to (2,3,3), (3,2,3) or (1,2). An nteresting space is defined as a collection of paths between adjacent ntersections. Finally, an ncredible maze is defined as an nteresting space combined with two specific ntersections in that space, one of which is identified as the starting ntersection and the other as the ending ntersection.
The input file will consist of the descriptions of one or more ncredible mazes. The first line of the description will specify n, the dimension of the nteresting space. (For this problem, n will not exceed 10, and all coordinate vectors will be less than 10.) The next line will contain 2n nonnegative integers, the first n of which describe the starting ntersection, least dimension first, and the next n of which describe the ending ntersection. Next will be a nonnegative number of lines containing 2n nonnegative integers each, identifying paths between adjacent ntersections in the nteresting space. The list is terminated by a line containing only the value 1. Several such maze descriptions may be present in the file. The end of the input is signalled by space dimension of zero. No further data will follow this terminating zero.
For each maze, output it's position in the input; e.g. the first maze is "Maze #1", the second maze is "Maze #2", etc. If it is possible to travel through the ncredible maze's nteresting space from the starting ntersection to the ending ntersection, also output "can be travelled" on the same line. If such travel is not possible, output "cannot be travelled" instead.
2 0 0 2 2 0 0 0 1 0 1 0 2 0 2 1 2 1 2 2 2 1 3 1 1 1 1 2 3 1 1 2 1 1 3 1 1 3 1 2 3 1 1 1 1 1 0 1 1 0 1 0 0 1 0 0 0 0 0 1 0
Maze #1 can be travelled Maze #2 cannot be travelled______________________________________________________ 2090false
Consider the two networks shown below. Assuming that data moves around these networks only between directly connected nodes on a peertopeer basis, a failure of a single node, 3, in the network on the left would prevent some of the still available nodes from communicating with each other. Nodes 1 and 2 could still communicate with each other as could nodes 4 and 5, but communication between any other pairs of nodes would no longer be possible. Node 3 is therefore a Single Point of Failure (SPF) for this network. Strictly, an SPF will be defined as any node that, if unavailable, would prevent at least one pair of available nodes from being able to communicate on what was previously a fully connected network. Note that the network on the right has no such node; there is no SPF in the network. At least two machines must fail before there are any pairs of available nodes which cannot communicate.
The input will contain the description of several networks. A network description will consist of pairs of integers, one pair per line, that identify connected nodes. Ordering of the pairs is irrelevant; 1 2 and 2 1 specify the same connection. All node numbers will range from 1 to 1000. A line containing a single zero ends the list of connected nodes. An empty network description flags the end of the input. Blank lines in the input file should be ignored.
For each network in the input, you will output its number in the file, followed by a list of any SPF nodes that exist. The first network in the file should be identified as "Network #1", the second as "Network #2", etc. For each SPF node, output a line, formatted as shown in the examples below, that identifies the node and the number of fully connected subnets that remain when that node fails. If the network has no SPF nodes, simply output the text "No SPF nodes" instead of a list of SPF nodes. Output a blank line between each block.
1 2 5 4 3 1 3 2 3 4 3 5 0 1 2 2 3 3 4 4 5 5 1 0 1 2 2 3 3 4 4 6 6 3 2 5 5 1 0 0
Network #1 SPF node 3 leaves 2 subnets Network #2 No SPF nodes Network #3 SPF node 2 leaves 2 subnets SPF node 3 leaves 2 subnets______________________________________________________ 2091false
As shown above, there is only one lane leading to the starting line. So the racing cars should be line up at the starting line in the order of their numbers which have been assigned according to the records in the preliminary race. When the cars arrive at the main entrance in a certain order, we want to find out whether we can rearrange the cars in the increasing order of their numbers by using a onelane bypass. Note that the cars should move only forward as designated by the arrows shown in the figure. Also, note that the cars in the bypass should be in a line because the bypass has only one lane. You can assume that the bypass is long enough to accommodate all the cars which participate in the race.
For instance, suppose there are four competitors and they arrive in the order 1, 3, 2, 4. Then we can rearrange the cars so that they can line up in the order 1, 2, 3, 4 at the starting line as follows: let the car numbered `1' first reach the starting line and the car numbered `3' enter the bypass and wait for the car numbered 2. After the car numbered `2' reach es the starting line, the car numbered `3' comes out from the bypass and arrives the starting line . Finally the car numbered 4 reaches the starting line.
The input consists of several test cases. The first line of the input file contains an integer representing the number of test cases. Each test case begins with a line containing an integer N, indicating the number of cars which participate in the race. The following line represents a permutation of N cars, numbered 1, 2,..., N. The consecutive car numbers are separated by a single space. Assume that N is less than 100.
Print exactly one line for each test case in the output. The line should contain ``YES" if the test case can be rearranged, and contain ``NO" otherwise .
2 4 1 3 2 4 3 3 2 1
YES NO______________________________________________________ 2092false
Chulsoo is working parttime at KAIST Central Library. His job is to collect books that have been left on desks by careless users and to relocate them into their original positions on bookshelves. To do this job efficiently Chulsoo collects the books and puts them on a long bookshelf, which is left empty for him, and then sort these books according to their call numbers. He carries the sorted books on a cart, and walks around bookshelves to restore th em into proper places.
One of the most difficult tasks for Chulsoo is to sort a number of books on his bookshelf according to their call numbers. He usually selects two books that are ``out of order" and swaps them, and selects another two books that are ``out of order" and swaps them, and repeats this ``selectandswap" process until all books are sorted. We say that two books are ``out of order" if one with smaller call number is to the right of another with larger call number.
You are to write a program to sort the books using a minimum number of swaps in ascending order of their call numbers.
The first line of the input file contains one integer t representing the number of test cases. Each case is described by two lines: the first line contains one integer n, which is the number of books on Chulsoo's bookshelf, and the second line contains a sequence of n positive integers, in which the ith integer is the call number of the book at position i. Assume that the call numbers of the books are all different and each of them does not exceed 10,000. Also, assume that n does not exceed 1,000.
Your program should print a sequence of t integers. The ith integer is the number of swaps for the ith test case that your program has computed.
2 5 25 347 12 19 203 7 55 101 47 61 82 11 96
3 4
______________________________________________________ 2093false
Venture MFG Company, Inc. has made a game board. This game board has 15 holes and these holes are filled with pegs except one hole. A peg can jump over one or more consecutive peg s to the nearest empty hole along the straight line. As a peg jump over the pegs you remove them from the board. In the following figure, the peg at the hole number 12 or the peg at the hole number 14 can jump to the empty hole number 5. If the peg at the hole number 12 is moved then the peg at the hole number 8 is removed. Instead, if the peg at the hole number 14 is moved then the peg at the hole number 9 is removed.
Write a program which find a shortest sequence of moving pegs to leave the last peg in the hole that was initially empty. If such a sequence does not exist the program should write a message ``IMPOSSIBLE".
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case is a single integer which means an empty hole number.
For each test case, the first line of the output file contains an integer which is the number of jumps in a shortest sequence of moving pegs. In the second line of the output file, print a sequence of peg movements. A peg movement consists of a pair o f integers separated by a space. The first integer of the pair denotes the hole number of the peg that is moving, and the second integer denotes a destination (empty) hole number.
1 5
10 12 5 3 8 15 12 6 13 7 9 1 7 10 8 7 9 11 14 14 5
______________________________________________________ 2094false
You are given n axisparallel rectangles on a plane. Here, an axisparallel rectangle is a rectangle whose edges are parallel to either xaxis or yaxis. You are to find the number of colors to paint the given n rectangles according to the following rules:
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case begins with a line containing an integer N, 1N200, that represents the number of rectangles in the test case. Each of the following N lines contains four positive integers x_{1}, y_{1}, x_{2}, and y_{2}, 1x_{1}, y_{1}, x_{2}, y_{2}10000, representing a rectangle. (x_{1}, y_{1}) and (x_{2}, y_{2}) are the (x, y)coordinates of the lowerleft and upperright corners of the rectangle, respectively. The four integers are delimited by one or more spaces. From the N + 3th line, the remaining test cases are listed in the same manner as above.
The output should contain the number of colors, one per line.
2 9 3 8 6 12 1 2 4 9 5 6 8 10 11 9 13 11 12 4 14 7 6 2 7 7 3 1 7 3 10 4 12 7 9 6 11 9 4 11 9 13 11 12 4 14 7 10 4 12 7 9 6 11 9
2 1
______________________________________________________ 2095false
N men and N women who are registered to the company want to marry as soon as possible. Each man and each woman have a list of preferences for all the people of the opposite sex. The most preferable person will come at the first position in the list, the second preferable person will come at the next, and so on. The table below shows a set of preference lists that might exist among 4 men and 4 women.
M_{1}  W_{2} W_{4} W_{1} W_{3}  /SPAN>  W_{1}  M_{4} M_{1} M_{2} M_{3} 
M_{2}  W_{1} W_{2} W_{3} W_{4}  /SPAN>  W_{2}  M_{4} M_{3} M_{2} M_{1} 
M_{3}  W_{2} W_{3} W_{4} W_{1}  /SPAN>  W_{3}  M_{1} M_{4} M_{2} M_{3} 
M_{4}  W_{1} W_{3} W_{2} W_{4}  /SPAN>  W_{4}  M_{3} M_{2} M_{1} M_{4} 
Your task is to make matches of all the men to all the women in such a way as to respect all their preferences as much as possible. However, you must assume that anyone assigned to someone other than the ir first choice will be disappointed and will always prefer anyone higher up on the list. If the N matches are chosen such that there exist a man and a woman who are not married on each other, but who would both prefer each other to their actual marriage partners, then the matches are said to be unstable. If no such pair exists, it is called stable. For example, a match `` M_{1}W_{3} M_{2}W_{1} M_{3}W_{4} M_{4}W_{2}" is unstable because M_{1} prefers W_{1} to W_{3}, and W_{1} prefers M_{1} to M_{2}. The unstable couples might be separated easily after marriage; this is a definitely bad situation that you want to avoid.
In general, there are many different stable matches for a given set of preference lists. Your task is to print just one stable match among them.
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case begins with a line containing an integer N less than 100, indicating that N men and N women are given. The following N lines repres ent the men's preferences for the women, where the ith line contains the preference list of a man with id i in order of preferences of the N women; he prefers a woman X to another woman Y if X precedes Y in the list. The following N lines represent the women's preferences for the N men. Assume that all men and all women have consecutive idnumbers from 1 to N.
Print exactly one line for each test case. The line should contain a stable match for the test case. Each match should be represented as a sequence of the women's id, according to the increasing order of men's id. The woman with the first id in the match is a partner of the man with id `1', the woman with the second id in the match is a partner of the man with id `2', and the woman with the ith id in the match is a partner of the man with id `i'. The consecutive women's id in the match should be separated by a single space.
2 6 6 1 4 5 2 3 2 3 5 4 1 6 2 1 5 3 6 4 4 5 6 2 3 1 6 3 4 5 2 1 6 4 1 3 5 2 5 6 4 2 3 1 4 6 1 5 3 2 5 4 3 1 6 2 4 3 1 6 2 5 5 3 4 6 2 1 3 2 6 4 5 1 3 1 2 3 3 2 1 2 1 3 1 2 3 3 2 1 2 1 3
2 5 1 4 3 6 1 3 2
______________________________________________________ 2096false
Taekwondo is the name of a traditional Korean martial art and it is turned into a modern international sport. It is adopted by IOC (International Olympic Committee) as an official game of 2000 Sydney Olympic Games. In Taekwondo, there are individual competitions and team competitions. An individual competition is conducted by two players and a team competition is a set of individual competitions. For two groups of players, we are going to make a team competition where two players for each individual competition are selected from each group. Note that players in each group can participate at most one individual competition. For fair competition, weights of two players in each individual competition must be very close. Given weights of players in two groups, you are to write a program to find pairs of players so that the sum of the absolute differences of theweights of two players in each competition is minimized.
The input file consists of several test cases. The first line of the input file contains an integer representing the number of test cases. The first line of each test case contains two integers. The first integer, n_{1}, is the number of players in the first group, and the second integer, n_{2}, is the number of players in the second group, where 1n_{1}, n_{2}500. You have to make min{n_{1}, n_{2}} pairs of players. Each line of the next n_{1} lines contains the weight of the player in the first group and the next n_{2} lines contain the weights of players in the second group. Weights of players are in the range of 40.0 to 130.0. You may assume that the precision of weight is one tenth.
The following sample input and corresponding correct output represents two test cases.
2 2 3 44.9 50.0 77.2 86.4 59.8 4 2 44.9 50.0 77.2 86.4 59.8 58.9
42.1 23.8______________________________________________________ 2097false
Younghee an elementary school student just finished her homework. Today her teacher gave her several lists each containing distinct positive integers. The homework was to calculate every sum of each pair of integers in a list. The teacher gave students mutually different lists for preventing copying out. So, she had to do the homework all by herself. It was hard job because she is not so good at arithmetic and pretty many lists were given. After finishing her homework Younghee went out to play with her friends. When Younghee returned to home she found out the lists were lost. Only the papers she wrote the sums were there. Younghee should return the lists at the next class because her teacher would check up her homework with the lists. Finally Younghee found out who did it. Her mother thought the lists as garbage and threw them into the garbage can and emptied it. Soon after listening to her mother, Younghee ran to the garbage box in the outside. Alas! The garbage colle ctor already emptied the box. After a little consideration Younghee thinks there might be a way to restore the lists. She calls you and asks you to help her.
In this problem, you are to solve Younghee's trouble. For each list of sums Younghee wrote, your program should restore the list of distinct integers. But, Younghee is not so good at arithmetic. So, there can be a list of sums which is not restorable, that is, there does not exist a list of integers which leads to the sums. In that case your program s hould print `1'.
The input contains T test cases. The first line of input contains a single integer (T) representing the number of test cases which is exactly the number of lists Younghee received from her teacher. Each test case begins with a line containing an integer n, 2 < n < 50, indicating the number of integers in a list. In the next line, there are n(n  1)/2 positive integers which are the sums of all possible pairs in nondecreasing order. Each number in the sums will be less than 10000.
Print exactly one line for each test case. The output should consist of n distinct positive integers in increasing order, if restorable. If not restorable, `1' should be printed. Numbers should be separated by a single space.
3 4 4 5 7 10 12 13 3 2 5 6 5 3 4 5 5 6 6 7 7 8 9
1 3 4 9 1 1 2 3 4 5
______________________________________________________ 2098false
Once upon a time the following puzzle was suggested to pupils on a regional middle school olympiad on mathematics:
A jury member was a trainer of a team of undergraduates for programming contests. So a question on how to put the puzzle for programming arose naturally. Fin ally the problem was formulated as follows:
The first line of input contains a single integer T that represents a total amount of different pairs (N, K) to process. Every line of next T lines contains two integers N, 2N100 and K, 0K100.
The output file should contain T lines with ``POSSIBLE" or ``IMPOSSIBLE" per line.
3 6 2 10 2 15 3
POSSIBLE IMPOSSIBLE POSSIBLE______________________________________________________ 2099false
The Contortion Brothers are a famous set of circus clowns, known worldwide for their incredible ability to cram an unlimited number of themselves into even the smallest vehicle. During the offseason, the brothers like to get together for an Annual Contortionists Meeting at a local park. However, the brothers are not only tight with regard to cramped quarters, but with money as well, so they try to find the way to get everyone to the party which minimizes the number of miles put on everyone's cars (thus saving gas, wear and tear, etc.). To this end they are willing to cram themselves into as few cars as necessary to minimize the total number of miles put on all their cars together. This often results in many brothers driving to one brother's house, leaving all but one car there and piling into the remaining one. There is a constraint at the park, however: the parking lot at the picnic site can only hold a limited number of cars, so that must be factored into the overall miserly calculation. Also, due to an entrance fee to the park, once any brother's car arrives at the park it is there to stay; he will not drop off his passengers and then leave to pick up other brothers. Now for your average circus clan, solving this problem is a challenge, so it is left to you to write a program to solve their milage minimization problem.
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
Each case will consist of one problem instance. The first line will contain a single integer n indicating the number of highway connections between brothers or between brothers and the park. The next n lines will contain one connection per line, of the form name1 name2 dist, where name1 and name2 are either the names of two brothers or the word Park and a brother's name (in either order), and dist is the integer distance between them. These roads will all be 2way roads, and dist will always be positive. The maximum number of brothers will be 20 and the maximumlength of any name will be 10 characters. Following these n lines will be one final line containing an integer s which specifies the number of cars which can fit in the parking lot of the picnic site. You may assume that there is a path from every brother's house to the park and that a solution exists for each problem instance.
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
For each test case, the output should consist of one line of the form
Total miles driven: xxx
where xxx is the total number of miles driven by all the brothers' cars.
2 10 Alphonzo Bernardo 32 Alphonzo Park 57 Alphonzo Eduardo 43 Bernardo Park 19 Bernardo Clemenzi 82 Clemenzi Park 65 Clemenzi Herb 90 Clemenzi Eduardo 109 Park Herb 24 Herb Eduardo 79 3 10 Alphonzo Bernardo 32 Alphonzo Park 57 Alphonzo Eduardo 43 Bernardo Park 19 Bernardo Clemenzi 82 Clemenzi Park 65 Clemenzi Herb 90 Clemenzi Eduardo 109 Park Herb 24 Herb Eduardo 79 1
Total miles driven: 183 Total miles driven: 255
______________________________________________________ 2100false
A polygonal number is a number which can be represented by a regular geometrical arrangement of equally spaced points, where the arrangement forms a regular polygon. Some examples are shown in the figure below.
Input
Input will consist of multiple problem instances. Each instance will consist of 3 lines. The first line will be a nonnegative integer n ≤ 50 indicating the number of types of polygonal numbers of interest in this problem. Note that this line may be longer than 80 characters. The next line will contain n integers indicating the indices of these polygonal numbers (all distinct and in increasing order). For example, if the first line contained the value 3, and the next line contained the values 3 610, then that problem instance would be interested in 3gonal, 6gonal and 10gonal numbers. Each index k will lie in the range 3 ≤ k ≤ 1000. The last line of the problem instance will consist of a single positive integer s ≤ 10000, which serves as a starting point for the search for polypolygonal numbers. A value of n = 0 terminates the input.
For each problem instance, you should output the next 5 polypolygonal numbers which are greater than or equal to s. Each number should be on a single line and conform to the following format:
num:k1 k2 k3 ...
where num is the polypolygonal number, and k1, k2, k3 ... are the indices (in increasing order) of the polypolygonal number equal to num. A single space should separate each index, and you should separate each problem instance with a single blank line. The judge's input will be such that the maximum value for any polypolygonal number will fit in a long variable.
10 6 7 8 9 10 11 12 13 14 15 1000 5 3 4 13 36 124 1 0
1216:9 12 1540:6 10 1701:10 13 2300:11 14 3025:12 15 1:3 4 13 36 124 36:3 4 13 36 105:3 36 171:3 13 1225:3 4 124
______________________________________________________ 2101false
A polynomial p(x) of degree n can be used to approximate a function f(x) by setting the coeficients of p(x) to match the first n coeficients of the power series of f(x) (expanded about x = 0). For example,
p(x)/q(x), where p(x) and q(x) are polynomials. You have been asked by Approximate Calculation Machinery to solve this problem, so they can incorporate your solution into their approximate calculation software.
Given m, n, and the first m + n coeficients of the power series of f(x), we wish to compute two polynomials p(x) and q(x) of degrees at most m1 and n1, respectively, such that the power series expansion of q(x)·f(x)p(x) has 0 as its first m+n1 coefficients, and 1 as its coefficient corresponding to the x^{m+n1} term. In other words, we want to find p(x) and q(x) such that
Background Definitions
A polynomial p(x) of degree n can be written as p_{0} + p_{1}·x + p_{2}·x^{2} + ... + p_{n}·x^{n}, where p_{i}'s are integers in this problem.
A power series expansion of f(x) about 0 can be written as f_{0} + f_{1}·x + f_{2}·x^{2} + ..., where f_{i}'s are integers in this problem.
The input will consist of multiple cases. Each case will be specified on one line, in the form
m n f_{0} f_{1} ... f_{m+n1}
where f_{i} is the coefficient of x^{i} in the power series expansion of f. You may assume that 1≤m, 1≤n≤4, 2≤m+n≤10, and f_{i} are integers such that f_{i}≤5. The end of input will be indicated by a line containing m=n=0, and no coefficients for f. You may assume that there is a unique solution for the given input.
For each test case, print two lines of output. Print the polynomial p(x) on the first line, and then q(x) on the second line. The polynomial p(x) should be printed as a list of pairs (p_{i},i) arranged in ascending order in i, such that p_{i} is a nonzero coefficient for the term x^{i}. Each nonzero coefficient p_{i} should be printed as a/b, where b > 0 and a/b is the coefficient expressed in lowest terms. In addition, if b = 1 then print only a (and omit b). If p(x) = 0, print a line containing only (0,0). Separate the pairs in the list by one space. The polynomial q(x) should be printed in the same manner. Insert a blank line between cases.
2 2 0 0 1 1 4 2 1 2 3 4 5 2 1 1 2 3 1 4 5 0 2 12 0 0
(0,0) (1,1) (4/33,0) (1/11,1) (2/33,2) (1/33,3) (4/33,0) (5/33,1) (2/3,0) (1/3,0) (25/6,0) (5/6,0) (1/3,2) (1/6,3)
______________________________________________________ 2102false
Consider the following pattern of positive integers:
3 3 1
3 1
2
Note that each row is leftjustified and no longer than its preceding row. Also, the entries in each row, when read left to right, are nonincreasing and the entries in each column, when read top to bottom are nonincreasing. We will call such a pattern a stacking pattern (SP) because such a pattern can represent a way of stacking cubes in a corner in the following way: if you consider placing the topmost row and leftmost column against walls, then the SP gives a bird'seye view of how many cubes are stacked vertically. The SP above represents the following corner stacking:
We will call the wall against the topmost row the right wall , and the wall against the leftmost column the left wall. Here is another SP and the corner stacking it represents:
6 5 5 4 3 3 6 4 3 3 1 6 4 3 1 1 4 2 2 1 3 1 1 1 1 1
3 2 1
2 1 1
2 1
3 3 2
2 1 1
1
You should check that both the left and right rotations of the second example SP are identical to the original SP.
This problem will consist of multiple problem instances. Each problem instance will consist of a positive integer n <= 11 indicating the number of rows in the SP that follows. (n = 0 indicates the end of input.) The rows of the SP will follow, one per line with entries separated by single spaces, delimited by a trailing 0. (The trailing 0 is, of course, not part of the input data proper and you may assume that each row given has at least one cube.) Each entry in the pattern proper will be a positive integer less than or equal to 20 and there will be no more than 20 entries in any row.
For each input SP you should produce two stacking patterns corresponding to the left rotation and the right rotation (in that order). Rows of the SP should be leftjustified with entries separated by a single space. One blank line should separate the left and right rotations of the given SP and two blank lines should separate output for different problem instances.
3 3 3 1 0 3 1 0 2 0 6 6 5 5 4 3 3 0 6 4 3 3 1 0 6 4 3 1 1 0 4 2 2 1 0 3 1 1 0 1 1 1 0 0
3 2 1 2 1 1 2 1 3 3 2 2 1 1 1 6 5 5 4 3 3 6 4 3 3 1 6 4 3 1 1 4 2 2 1 3 1 1 1 1 1 6 5 5 4 3 3 6 4 3 3 1 6 4 3 1 1 4 2 2 1 3 1 1 1 1 1
______________________________________________________ 2103false
The game of checkers is played on an 8 by 8 redblack board using alternate squares. Two players (Red and White) each start with 12 pieces which are set up in the starting position shown below:
Rules for movement and capture are as follows (Note: a forward move is one in which a piece moves towards the opponent's side of the board):
1. Players alternate moves.
2. A piece may move one square forward diagonally to any empty square.
3. A piece may jump forward over an opposing player's piece if the opposing piece is adjacent to the piece and the square directly beyond the opposing piece is empty. After a jump, the opposing piece is removed from the board (captured). If after a jump, the jumping piece can make another jump, it must do so. This continues until it can make no other jumps. This is called a multiple jump.
4. A player must make a jump if possible. If several jumps are possible, the player may choose any, even choosing a single jump over a multiple jump. (However, if a multiple jump is chosen, it must be completed.)
5. The last row on the opponent's side of the board (the row where the piece can make no more forward moves) is the player's promotion row. When a piece reaches the promotion row it is promoted to a king and may now move and capture backward as well as forward. Once a piece is promoted, its move endsit cannot start to jump or continue a multiple jump after becoming a king until the next turn.
6. A piece may be jumped at most once during a move (only a consideration when a king is doing the jumping).
Games are recorded using the square numbering shown above. For example, a simple forward move for White might be 2218; a single jump for Red might be 14{23 (capturing a White piece at square 18); and a multiple jump for a White king might be 22312415 (capturing Red pieces at 26, 27 and 19).
For this problem, you will be given a position of a game in progress and a set of moves to be applied starting at that position, and you must determine if all the moves are legal by writing an Advanced Checkers Machine.
Input will consist of multiple problem instances. Each instance will start with two integers r and w, indicating the number of Red and White pieces on the board (values of r = w = 0 indicates end of input, otherwise 1 <= r; w <= 12). The next line will contain r square numbers indicating the Red piece positions and the next line will contain w square numbers for the White piece positions. Positive square values will indicate that a normal piece lies on that square, while a negative value sq will indicate that a promoted piece lies on square sq. The next line will contain a single integer m >= 1 indicating the number of moves to make, followed by a space and then a single character (either R or W) indicating whose move it is. The next m lines will contain the m moves, using the notation described above. (You may assume that there are no more than 13 square numbers listed in any one move.)
All board positions will be legal positions (e.g., there will never be two pieces occupying the same square). You may assume that pieces that have advanced to their promotion row are indeed promoted; that is, there will be no pieces on their promotion row that are not kings.
For each problem instance, output either All moves valid or Move n is invalid, where n=1 corresponds to the firrst move in the problem instance. If there are multiple illegal moves, you should list only the first such move.
4 3 6 7 8 16 9 18 19 3 W 92 162314 2114 4 3 6 10 15 19 18 22 23 6 R 1926 1811 1014 2218 610 1015 0 0
All moves valid Move 5 is invalid______________________________________________________ 2104false
Alexander Charles McMillan loves to gamble, and during his last trip to the casino he ran across a new game. It is played on a linear sequence of squares as shown below.
A chip is initially placed on the Start square. The player then tries to move the chip to the End square through a series of turns, at which point the game ends. In each turn a coin is flipped: if the coin is heads the chip is moved one square to the right and if the coin is tails the chip is moved two squares to the right (unless the chip is one square away from the End square, in which case it just moves to the End square). At that point, any instruction on the square the coin lands on must be followed. Each instruction is one of the following:
1. Move right n squares (where n is some positive integer)
2. Move left n squares (where n is some positive integer)
3. Lose a turn
4. No instruction
After following the instruction, the turn ends and a new one begins. Note that the chip only follows the instruction on the square it lands on after the coin ip. If, for example, the chip lands on a square that instructs it to move 3 spaces to the left, the move is made, but the instruction on the resulting square is ignored and the turn ends. Gambling for this game proceeds as follows: given a board layout and an integer T, you must wager whether or not you think the game will end within T turns.
After losing his shirt and several other articles of clothing, Alexander has decided he needs professional helpnot in beating his gambling addiction, but in writing a program to help decide how to bet in this game.
Input will consist of multiple problem instances. The first line will consist of an integer n indicating the number of problem instances. Each instance will consist of two lines: the rst will contain two integers m and T (1 <= m <= 50, 1 <= T <= 40), where m is the size of the board excluding the Start and End squares, and T is the target number of turns. The next line will contain instructions for each of the m interior squares on the board. Instructions for the squares will be separated by a single space, and a square instruction will be one of the following: +n, n, L or 0 (the digit zero). The first indicates a right move of n squares, the second a left move of n squares, the third a loseaturn square, and the fourth indicates no instruction for the square. No right or left move will ever move you off the board.
Output for each problem instance will consist of one line, either
Bet for. x.xxxx
if you think that there is a greater than 50% chance that the game will end in T or fewer turns, or
Bet against. x.xxxx
if you think there is a less than 50% chance that the game will end in T or fewer turns, or
Push. 0.5000
otherwise, where x.xxxx is the probability of the game ending in T or fewer turns rounded to 4 decimal places. (Note that due to rounding the calculated probability for display, a probability of 0.5000 may appear after the Bet for. or Bet against. message.)
5 4 4 0 0 0 0 3 3 0 1 L 3 4 0 1 L 3 5 0 1 L 10 20 +1 0 0 1 L L 0 +3 7 0
Bet for. 0.9375 Bet against. 0.0000 Push. 0.5000 Bet for. 0.7500 Bet for. 0.8954______________________________________________________ 2105false
When rendering a scene with multiple objects onto a screen, the order in which the objects are drawn is very important. In general, the farther an object is from the screen, the earlier it should be drawn allowing later, closer objects to be drawn on top of them. If two objects do not overlap, the order of drawing is immaterial. A binary spacepartitioning (BSP) tree is one type of data structure which attempts to simplify the determination of the ordering of objects. It works as follows. Assume that the screen lies in the xyplane centered on the zaxis and that the zaxis points away from the user looking at the screen. (For our purposes, assume the user lies near  ∞ on the zaxis.) We also assume that all the objects lie on the opposite side of the screen (z > 0). The BSP tree is built by placing a series of planes parallel to the yaxis. The first plane divides space into two regions: a region containing the viewer and a region not containing the viewer. We partition all objects in space according to which of these two regions they lie in, and observe that all objects in the region containing the viewer should be drawn after all the objects in the other region. The BSP tree can be viewed at this point as a root with only two children, each child containing one of the partitions. We can now add a second plane, which subdivides the space again. We split each of the two partitions from the rst plane in two, making a total of 4 partitions, and the resulting BSP tree now has three levels, with the partitions in the leaves (note that some of these partitions may contain several objects and some may contain none). This process is continued until each partition has at most one object in it, or until some predetermined number of planes has been used. The diagram below gives an example of using 1, 2 and 3 planes (looking down along the yaxis). For simplicity we assume that all objects lie parallel to the zaxis, so we need only deal this 2d image to determine the BSP tree.
Assuming you have split the partitions correctly, a simple traversal of the BSP tree will give you an appropriate ordering for which to render the objects in the scene. Note in the example above that once a node contains just one object it need not be split as additional planes are added.
Input will consist of several problem instances. The first line of each instance will contain a positive integer n <= 20 indicating the number of objects in the scene. The next n lines will contain a description of these objects using the format m x1 z1 x2 z2 .. xm zm, where m is the number of vertices in the object and the remaining values are the vertices of the intersection of the object with the xzplane. All objects will have between 3 and 6 vertices. Objects are assumed to be labeled "A", "B", "C", ... in the order they are defined. Next in the input le will be a positive integer p <= 10 indicating the number of planes used to create the BSP tree. The last p input lines will contain a description of each plane of the form x1 z1 x2 z2 representing two points on the intersection line of the plane and the xzplane. You may assume that no line will intersect any object (including edges and vertices) and that no plane is parallel to the zaxis. All coordinates will be integers.
Output will consist of a single line for each instamce containing the names of the objects in the order that they should be rendered for the specified BSP tree. In the case when some partition contains two or more objects, you should list the objects in alphabetical order.
10 3 65 5 66 5 65 6 3 65 123 66 123 65 124 3 122 176 123 176 122 177 3 56 23 57 23 56 24 3 11 49 12 49 11 50 3 167 111 168 111 167 112 3 57 123 58 123 57 124 3 130 6 131 6 130 7 3 100 85 101 85 100 86 3 11 28 12 28 11 29 10 159 165 131 177 153 192 197 158 77 86 98 30 177 59 146 63 192 117 92 43 121 67 62 134 41 81 130 196 95 185 89 154 163 179 93 175 113 41 92 28
BCGEJFIHDA
______________________________________________________ 2106false
Alice Catherine Morris and her sister Irene Barbara frequently send each other emails. Ever wary of interceptions and wishing to keep their correspondence private, they encrypt their messages in two steps. After removing all nonalphabetic characters and converting all letters to upper case, they: 1) replace each letter by the letter s positions after it in the alphabet (1 ≤ s ≤ 25)  we call this a shift by s and then, 2) divide the result of step 1 into groups of m letters and reverse the letters in each group (5 <= m <= 20). If the length of the message is not divisible by m, then the last k (less than m) letters are reversed. For example, suppose s = 2 and m = 6. If the plaintext were
Meet me in St. Louis, Louis.
after removing unwanted characters and changing to upper case we get
MEETMEINSTLOUISLOUIS
We will call this the modi ed plaintext. We then shift each letter by 2 (Y would be replaced with A and Z would be replaced by B, here), getting the intermediate result:
OGGVOGKPUVNQWKUNQWKU
And finally reverse every group of 6 letters:
GOVGGOQNVUPKWQNUKWUK
Note the last two letters made up the last reversed group. As is customary, we write the result in groups of 5 letters. So the cipher text would be:
GOVGG OQNVU PKWQN UKWUK
Alas, it's not so hard to find the values for s and m when the cipher text is intercepted. In fact it's even easier if you know a crib, which is a word in the modified plaintext. In the above example, LOUIS would be a crib. Your job here is to find s and m when presented with a cipher text and a crib.
Input will consist of multiple problem instances. The first line of input will contain a positive integer indicating the number of problem instances. The input for each problem will consist of multiple lines. The first line of input for a problem will contain the integer n (20 <= n <= 500) which is equal to the number of characters in the ciphertext. The following lines will contain the ciphertext, all upper case in groups of 5 letters separated by a single space. (The last group of letters may contain fewer than 5 letters.) There will be 10 groups of letters per line, except possibly for the last line of ciphertext. The input line following the last line of ciphertext will contain the crib; a single word consisting of between 4 and 10 (inclusive) upper case characters.
Output will be two integers, s and m on a line, separated by a single space, indicating the encryption key that produces the crib, where s is the shift and m is the reversed group size. If there is more than one solution, output the one with smallest s. If there is more than one with the same s, output the one with smallest m. If no such s and m exist, output the message Crib is not encrypted.
4 83 FIQMF IISFN QMFIB EOPFH FNQMV PSFIU IZNGP UPEUS BFPEP PEPPE PPEPN QMFIP EOPIS FIQMF IBSFN QMFBE OPI RHONDA 105 VDBMN DQDGS LNQEM ZLZRZ RNGVX ZALNA TERZV CZDGD MZQHZ GENKK KONSC DJHKC KKZAD RZAXZ SNMRH GBHGV RZVDG XZRNS XZKOS ZCNNF SHFMH BOMBAY 50 QFNWX YQFNW YSAQX FYNWY XQFNW SXYQF FXNYS AXYQF NASXY QFNAX HEAVEN 20 GOVGG OQNVU PKWQN UKWUK LOUIS
1 6 25 6 Crib is not encrypted. 2 6
______________________________________________________ 2107false
The ToxicCo chemical company has developed a new, somewhat unstable process for electroplating metals in a hot acid bath. This process requires constant monitoring of the temperatures and voltages present in the bath. Too low a temperature or too high a voltage will cause the dissolved metals to congeal in a mass at the bottom of the vat, damaging the equipment. On the other hand, if the temperature gets too high, acid fumes may be released into the atmosphere. If the voltage goes too low, the chemical reaction is altered, and an explosion becomes possible.
A stateoftheart, artificiallyintelligent process controller is supposed not only to keep the vat temperature and voltage at safe levels, but also to continually adjust them so as to maximize the speed of the electroplating process. Unfortunately, the software developers have reported that ``there's still a few bugs in the system" and won't promise delivery of the controller for at least another 9 months. (A few malcontents within the company are beginning to question whether the development team, headed by the nephew of the ToxicCo company president, will ever deliver a working system.)
This plant needs to start operation as soon as possible, so you have been commissioned to write a simpler control program to serve in the interim while the delux version is being debugged.
Write a program to read descriptions of "safe regions" within which temperature and voltage levels can range and to read current temperatures and voltage values and then to determine if the current values are safe. A safe region is described by 4 linear constraints:
The safe region forms a quadrilateral in the (T, V) coordinate space, and is guaranteed to be closed (i.e., the safe region does not include plus or minus infinity for either T or V).
All input to this program is supplied from the standard input stream. The input begins with a line containing an integer value indicating the number of data sets to follow. There will be at least one data set, but no more than 500.
Each data set consists of 5 lines of text, as follows
On each line, the indicated values will be given as floating point numbers, separated from one another by one or more blanks. No line will exceed 80 characters.
The output of this program will consist of a single line of text per data set, written to the standard output. Each line will contain the data set number, leftjustified, a blank, and then either the word `SAFE' or the word `UNSAFE', followed by the appropriate endofline termination. No other output should appear.
2 35.0 5.0 375.0 0.0 1.0 65.0 10.0 32.5 3000.0 55.0 30.0 1350.0 15.0 75.2 35.0 5.0 375.0 0.0 1.0 65.0 10.0 32.5 3000.0 55.0 30.0 1350.0 25.0 70.6
1 UNSAFE 2 SAFE
______________________________________________________ 2108false
Bill and Scott are business rivals. Each of them wishes to buy a house in Javaville, but they want to live as far away from each other as possible. Since Javaville is a relatively new town, there are no maps available yet; instead, information about homes and other buildings has been collected by word of mouth and provided to both Bill and Scott. This information consists of building addresses and distances between buildings. All of the information is consistent, although it may be incomplete or redundant.
The streets in Javaville are laid out in a rectangular grid of m east/west streets (named A, B, C, ...) and n north/south streets (numbered 0, 1, 2, ...), where m and n are each between 2 and 10. Every building (either a house or some other building, such as a post office or school) in Javaville is at the intersection of two streets, and no two buildings are located at the same intersection. Some intersections have no buildings at all. All distances are measured in terms of the smallest number of whole blocks that must be traversed north, south, east, and/or west to get from one intersection to another intersection. It is know that there are no more than 50 intersections in the entire town.
Here is some sample information that might be provided to Bill and Scott by various reliable sources:
From this we can see that there are two possible maps of Javavillesee Figure 1.
0 1 2 3 4 0 1 2 3 4 A h1oooP A h1oooP                     B ooooo B ooooo                     C h2oooo OR C h3oooo                     D oSooo D oSooo                     E ooh3oo E ooh2oo Figure 1: h1,h2,h3 = houses, P = postoffice, S = school
We see that the locations of house1, the post office, and the school are fixed, but house2 could be at either C0 or E2, and house3 could be at either C0 or E2. Clearly there is always a pair of houses separated by 6 blocks (house1 is always 6 blocks from the furthest house), but the best distance we can guarantee for any specific pair of houses is 4 (since house2 is always 4 blocks away from house 3). We would report this information to Bill and Scott, telling them that, even though a separation of 6 is always achievable, the safest recommendation that we are able to make for specific houses is to have one of them purchase house2 and have the other purchase house3. (We assume that Bill and Scott will consult with one another before purchasing their houses in order to guarantee that one of our recommendations is followed.)
Bill and Scott would like you to write a program that will take location and distance information about buildings and determine two quantities, D and D'. D is the minimum, over all possible valid arrangements of buildings, of the largest house separation in each arrangement. D' is the maximum value for which there exists a pair of houses i and j that are guaranteed to be separated by a distance of at least D'. In the latter case, you should list all pairs of houses that are guaranteed to be separated by at least D' blocks.
To make sure your program is working correctly, Bill and Scott would like to be able to test it on multiple data sets, so your program will be presented with several hypothetical descriptions of Javaville.
The input will consist of one or more descriptions. Each description will begin with a line containing two positive integers, m and n, representing the number of blocks in each direction ( 2m, n10). Each description will end with a line containing the single word `END' in uppercase. The entire data set will end with a line containing a pair of zeros. No assignment of values for m and n will result in a town having more than 50 intersections.
The remaining lines in each data set will be in one of the following two formats:
name LOCATION r c
or
name DISTANCE d name2
where name and name2 are strings containing only digits and lowercase alphabetic characters, each of length at most 10; r is an uppercase letter between A and J; c is a digit; and d is a positive integer. If the first five characters of a name are the lowercase letters `house' then it is a candidate for selection as a home for Bill or Scott; otherwise it stands for some nonresidential building. In a `DISTANCE' specification, name2 will always be the name of some building that has occurred previously in this data set as the first name on one of the data lines (in other words, there are no forward references to buildings in DISTANCE constraints). Each description is consistent (i.e., there is at least one way to lay out the houses and other buildings in a way consistent with the description). Each description will include information about at least two distinct houses. At most 20 distinct building names will occur in each description, and there will be at most 21 constraints (LOCATION or DISTANCE) for each description.
For each description, the output will consist of the description number, followed by the maximum achievable house separation D, followed by a list of all pairs of houses with maximum guaranteed separation D' (which might be smaller than the maximum achievable separation). No pair of houses should be listed more than once. The output should be labeled exactly as shown in the sample output below, with a blank line separating the outputs for consecutive data sets. In each pair, houses should be ordered according to the first time they appear in the input; the list of pairs should be ordered in the same way, sorted by the first element of the pair, then by the second element.
5 5 house1 LOCATION A 0 postoffice LOCATION A 4 school DISTANCE 4 house1 house2 DISTANCE 6 postoffice school DISTANCE 6 postoffice house3 DISTANCE 6 postoffice END 2 3 school LOCATION A 0 house1 DISTANCE 1 school house2 DISTANCE 1 house1 house3 DISTANCE 1 house2 house4 DISTANCE 1 house3 house5 DISTANCE 1 house4 END 0 0
DESCRIPTION 1 Maximum guaranteed separation is 6 blocks. Houses separated by at least 4 blocks: house2 house3 DESCRIPTION 2 Maximum guaranteed separation is 3 blocks. Houses separated by at least 2 blocks: house1 house3 house1 house5 house2 house4 house3 house5
______________________________________________________ 2109false
I.M. Crooked, general contractor, is looking for an easier way to give potential customers totally useless estimates of how much it will cost to build additions onto their houses. Although the final estimates aren't related to what the additions will cost, Mr. Crooked wants the estimates to be based on a formula so he can explain to the customers how he arrives at the estimate. You've been given the formula and must implement a program to automate his estimates.
There is a fixed base cost for adding on an addition; a cost per square foot of finished floor, ceiling, or wall; a cost per square foot of door; and a cost per square foot of window. Additionally, there are maximum widths and heights for standard doors or windows. If any window or door exceeds one of those dimensions, then the cost for that particular window or door is multiplied by a given factor.
Your program will accept a file which lists a set of prices, and then lists a set of potential additions. You must calculate and output the cost of each addition.
Each addition is a single room, and its definition will begin with a line:
room < width > < length > < height > < number of doors > < number of windows >
Immediately following that line will be one door line for each door:
door < width > < height >
Following all of the door lines will be one window line for each window:
window < width > < height >
The next addition will begin immediately following the last line belonging to the previous room.
The file will end with:
END OF INPUT
All numbers except the number of doors and the number of windows will be floating point numbers.
For each room, a single line of output will show the calculated price, rounded to the nearest penny. No dollar sign will be used:
10000 3.45 2.10 3 7 1.5 4.5 3 5 2.1 room 25 15 10 2 1 door 3 8 door 3 7 window 4 5 END OF INPUT
15431.95
______________________________________________________ 2110false
Lon Tymago, a professor of history, is having a difficult time training his students not to use the personal pronoun "I" when they write their term papers. Most of Dr. Tymago's students now submit their papers electronically, so the professor has hired you to write a program that will automatically scan the students' papers, identifying occurrences of the pronoun ``I". This will eliminate one step in grading the papers.
Unfortunately, history papers often make use of the Roman numeral ``I" (e.g., King George I, Pope John Paul I, World War I). Your program is not to indicate any error when it can be clearly determined that one of these situations has occurred.
The word ``I," used as a pronoun, frequently occurs immediately in front of a verb: ``I think," ``I am," ``I did," and so on. The same can be said of noun phrases such as ``King George I" and ``World War I": ``George I thinks," ``World War I is," and so on. However, some verb forms are appropriate for only one case. It is grammatically correct to write ``I think," but it is not correct to write ``George I think." Likewise, we can say ``I am," but we cannot say ``World War I am." Your program will make use of verb forms as part of its strategy for locating the pronoun ``I." Of course, in some cases the verb form is not enoughfor example, ``I had" and ``George I had" are both correct Your program should identify these as indeterminate cases requiring further scrutiny by Dr. Tymago.
One other clue helps distinguish valid uses of ``I" from invalid ones: the pronoun ``I" rarely appears immediately before a punctuation mark. (There are exceptions, of course, as in ``I, a student of history, ...," but we will assume that these exceptions will not occur in any of the student papers.)
You will first be given a list of verb pairs. Each pair will show a form correct for the firstperson singular pronoun ``I" and a form correct for a thirdperson noun (the two forms may be the same). Following this, you will be given several essays written by Dr. Tymago's students. Your program should print each line of text unchanged (including all white space, punctuation, etc.), preceded by a count of the number of positively identified uses of the firstperson pronoun ``I" and a count of the uses of ``I" that are possibly incorrect. In addition, these ``I"s should be marked as described below. Correct usages of ``I" (as determined by the verb forms or presence of punctuation) should not be counted or marked.
The data file will begin with a positive integer n (50) indicating the number of verb pairs, followed by n lines, each containing the firstperson and thirdperson forms of some verb, separated by a space. Each verb form is no longer than 20 letters. Following this will be one or more student essays. Each essay will consist of at most 25 nonempty lines, each consisting of at most 60 upper and lower case letters, spaces, and punctuation marks. There are no trailing blanks on the lines. The only permitted punctuation marks are periods (`.'), commas (`,'), exclamation points (`!'), and question marks (`?'). There are no other special characters (such as parentheses, tabs, hyphens, apostrophes, etc.), and lines are broken only between words or after punctuation marks. Each student paper will be followed by a line containing only the word `END'. The entire data file will be terminated by a line containing the words `END OF DATA'. You may assume that every verb which appears following the word ``I" will be one of the verb forms in the initial list, that the word ``I" will never appear in the text except followed by a verb form or a punctuation mark, and that no two distinct verbs will agree on their first and thirdperson forms.
Imitate the sample output below. Each student essay should be printed out, preceded by a line containing the number of the essay in the input sequence. Each line of student text should be exactly reproduced in the output, including all leading blanks, punctuation marks, etc., but shifted 8 spaces to the right. Beneath each line of text there should be an indicator line showing a `*' below every positively identified use of the pronoun ``I" and a `?' below each ``I" whose meaning cannot be determined according to the rules described above. A blank indicator line should follow text lines that have no indeterminate or incorrect usages of ``I". Trailing blanks are permitted in indicator lines as long as they do not cause the total line length to exceed 80 columns. In the eight spaces preceding each line of student text there should be two integers representing the number of occurrences of the pronoun ``I" and the number of indeterminate uses of the word ``I" (cases in which the rules are not sufficient to make a determination) for that line. A blank line should separate each student's paper from the next paper.
10 was was do does have has imitate imitates think thinks thought thought am is wonder wonders would would like likes World War I was many years after the Revolutionary War. I wonder what King George I would have thought of his grandson losing that war. Another king, Richard I, was nicknamed Richard the Lionhearted. I think I like him. END I would like to get an A on this paper about Pope Pius I, but I have no idea who he is. END END OF DATA
STUDENT 1 1 1 World War I was many years after the Revolutionary War. I ? * 0 1 wonder what King George I would have thought of his grandson ? 0 0 losing that war. Another king, Richard I, was nicknamed 2 0 Richard the Lionhearted. I think I like him. * * STUDENT 2 0 1 I would like to get an A on this paper about Pope Pius I, ? 1 0 but I have no idea who he is. *
______________________________________________________ 2111false
In the wake of the recent controversy over the intrusive questions asked by the US Census Bureau during the 2000 census, Congress has decided that decisive action is required and so, after much debate, it has decided to ... commission a factfinding study. The Census Bureau has been instructed to form discussion groups of people from around the country and of many different ancestries to help refine the questions for the 2010 census.
To encourage diverse responses, no two members of any discussion group can come from the same ancestry or from the same city. Furthermore, because these people will be together in small meeting rooms for some time, smokers should not be placed in the same group with nonsmokers. Finally, the caterer has suggested that serving lunch to these groups would be easier if vegetarians and nonvegetarians were not mixed together.
Write a program to read descriptions of the people participating in the factfinding study. Your program
should then assign these people to discussion groups so that no two people of the same ancestry are
together in a group, no two people from the same city are together in a group, no group contains a mixture
of smokers and nonsmokers, and no group contains a mixture of vegetarians and omnivores (non
vegetarians). The program should also enforce limits on the maximum number of discussion groups and
the maximum size of any one group. It is possible that, given such limits, assignment of all people into
groups may not be possible. The program should indicate in its output whether or not a suitable assignment
of people into groups is possible and, if it is possible, the membership of each group.
All input is taken from the standard input stream. The first line of input will contain two positive integers, separated by one or more blanks. The first integer is the maximum number of discussion groups permitted. The second is the maximum number of people per group.
Each subsequent line of input describes a single person participating in the study. Each person is implicitly identified by number according to the line in which their description occurs. The first line of input, as already noted, describes the number and size of groups rather than a person. Therefore the second line of input describes person #1, the third line describes person #2, etc.
Each person's description has the form:
Ancestry  code City  code
Smoker  code
Lunch  code
Each of the four codes is separated from the others by one or more blanks. The
Ancestry  code and
City  Code are positive integers. The
Smoker  code is either `S' or `N' (Smoker or NonSmoker).
The
Lunch  code is `V' or `O' (Vegetarian or Omnivore). The smoker and lunch codes will always
be uppercase letters. No line of input will exceed 80 characters.
The entire set of descriptions is terminated by endoffile on the input stream. There will be at most 200 descriptions.
All output is to the standard output stream.
If it is not possible to assign all the people to appropriate discussion groups, the program should print `NO ASSIGNMENT POSSIBLE'.
If an assignment is possible, then the program should print one line of output for each nonempty discussion group. Each line of output should contain the identifying numbers of the people assigned to that group, separated from one another by a single blank character. The numbers in each line may appear in any order. At the end of this listing of group assignments, the program should print `END OF GROUPS'. The `NO ASSIGNMENT POSSIBLE' or `END OF GROUPS' messages should appear by themselves on a single line starting in the first character position of that line.
Note that, for some inputs, there may be many acceptable assignments. The program may print any
acceptable assignment in such cases.
5 3 1 1 S V 2 3 S V 3 2 N O 1 3 S V 1 1 N O 4 4 N O 5 7 N O
1 2 5 6 3 4 7 END OF GROUPS
______________________________________________________ 2112false
The FAA's most recent plan to replace every computerized component of their traffic control system has failed. They have finally decided to replace only the most important part, the collision detection system. You have been given the responsibility of writing this lifecritical part of the system.
Your program receives input from an airport's radar
system. The radar system is very advanced and can
report the position, direction, and speed of any
airplane in the vicinity. The program must determine
if any plane it sees is likely to collide with any other
plane in the area.
The airport's radar spins at a continuous rate, completing one revolution every 4 seconds. Data is reported about each plane as the radar faces in that direction. As each plane's data is received, the program must determine if the new plane's course over the next 10 seconds will be too close to the course of another plane that has been seen by the radar within the past eight seconds.
The minimum requirement for proximity at this airport is that the planes always be separated by at least 2500 feet in all directions (standard three dimensional distance). If a test is made between the current plane and one seen previously, the previous plane's course is plotted by calculating where it would be at the current time if it has continued its last known direction over the time from when it was last seen to the present. For example, for a plane seen 3 seconds previously, that plane's course is plotted by calculating where it would be 3 seconds after its last observation; then the routes of the two planes over the subsequent 10 seconds is calculated. If, at any point during those 10 seconds, the planes would be within 2500 feet, the two planes are too close.
The input to the program consists of the series of radar observations. Anytime a plane's course will bring it
too close to another plane's course, the program will output a warning listing the two planes. If a new plane
is too close to multiple planes' flightpaths, the conflicts will be printed out from the most recently seen
plane to the least recently seen.
The radar spins clockwise. Note that a plane's course may not conflict with its own course seen previously by the radar. More than one plane may be found at a particular bearing of the radar. Planes with identical bearings may be listed in any order. The input will indicate when the plane spins through 0 degrees. Planes at a bearing of 0 degrees will always be listed after this indication.
Keep only one entry for each plane. Keep no entry older than 8 seconds.
HINT: compass degrees are in a different coordinate system than standard trigonometric degrees.
Because floating point errors may be introduced by different solutions to this problem, the data in all input
files will produce planes which pass either within 2490 feet or further than 2510 feet, so comparisons with
2500 feet are reliable.
Each line consists of:
< bearing > < PlaneID >
< distance from radar >
< elevation > < heading >
< rate of ascent >
< velocity >
All numbers are realvalued numbers. All numbers will be nonnegative, except for rate of ascent, which may be negative for descent. However, note that the courses over the next ten seconds may produce negative coordinates, in the case of a landing plane, for instance. Your program should allow such negative coordinates for landing planes (do not force altitude to stay positive). The total length of the line will not exceed 150 characters.
A line of:
CLICK
indicates that the radar has spun through 360 degrees.
The file will terminate with
END OF INPUT
Output is only produced in the case of planes' courses being too close, in which case the PlaneID of the justspotted plane is printed followed by the PlaneID of the previously seen plane. In the case of multiple proximity violations, print all conflicts on separate lines, with the most recently seen conflicting plane being printed first.
0 planeA 1 10000 0 0 .2 75 planeB 5.79 10000 270 0 1 270 planeC 2500 10000 0 0 .2 END OF INPUT
planeB planeA planeC planeB
______________________________________________________ 2113false
"Louie, I bet you that there are over 200 ways to make change for a dollar."
"You're on Frankie, there are only 5 coins and its only 100 cents. Everyone knows there can only be 100 different ways."
"Oh yeah, I can prove it. Watch."
Write a program that determines the number of ways the following US coins can be combined to make amounts of money up to and including 2 dollars.
Penny  $0.01
Nickel  $0.05
Dime  $0.10
Quarter  $0.25
Half Dollar  $0.50
The input will consist of a sequence of lines, each line indicating the amount of change required. Input terminates with a value of 0.
For each input value, a line indicating `There are X ways to make $
Y' where X is the number of ways, and Y is the input value. Each input set should have one line of output.
After all inputs sets have been run, the program will print `End of Output'.
1.00 0.51 0
There are 292 ways to make $1.00 There are 50 ways to make $0.51 End of Output
______________________________________________________ 2114false
Even in ancient times when sea commerce was conducted entirely by sail or rowing, harbors were sometimes mined to discourage unwelcome visitors (smugglers, raiders, etc.). Of course, in pregunpowder eras, the harbor would be blocked, not with explosives. Instead, nets, chains, sunken derilict ships and other debris, lying a little below the waterline, could rip the bottom out of a ship, or at least strand a ship long enough for shorebound archers and siege engines to come to bear.
When ships arrived on legitimate business, a local pilot would row out to meet it, board the ship, and guide it into port through the safe channels left between the underwater obstacles. The location of these safe passages was, of course, a closelyheld secret that would prove invaluable to a city's enemies. An agent for an unfriendly power has received a description of the passage through one such harbor and has been instructed to attempt the passage late at night to verify the accuracy of the information. If the information is correct, a fullscale invasion will follow.
"The harbor of Algorithmos is shaped by two narrow arms of land, as shown in the accompanying map, with the open end to the north. The west and east ends of the opening are 100 stadia apart. Beacon fires, marked "A" and "B" on the map, are maintained at the ends of the two arms. At night, you will have to navigate by reference to these beacons. Starting from the midpoint of the line between those beacons, your directions are as follows..."
There follows a set of instructions of the form
``SE 10 stadia, WSW 5 stadia, S 15 stadia, ..."
The agent sets out with two sailors in a small boat with a compass and a pair of sextants (navigational
instruments) that allow each sailor to measure the angle between the beacon fires and north (as indicated by
the compass). They call these angles out to the agent, who must determine when they have completed a
``leg" of the instructions.
Write a program that reads in the instructions for the safe path and prints, for each leg of the journey, the
angles of the two beacons at the end of that leg. The directions
given in the input instructions and the measurement of angles
should be conducted with respect to the conventional compass
rose, as shown here. (All angles should be expressed in the range
from 0 up to but not including 360, where North is 0, East is 90,
NE is 45, NNE is 22.5, etc.)
You may assume that the beacons A and B lie exactly on an East West line from one another, and are exactly 100 stadia apart. The safe path begins at the point 50 stadia from each beacon. You may assume that no safe path ever goes north of the EastWest line between the beacons.
For each leg of the journey, you should print the heading (angle) of the two beacons on the compass rose as observed from the boat at end of that leg. Because of the limitations in measurement technology of the time, these outputs will be rounded to the closest degree.
All input is taken from the standard input stream, and consists of several datasets. The first line of the input indicates the number of datasets.
There will be a blank line before each dataset. The first line of each dataset consists of a single integer indicating the number of legs of the complete safe path. Each line after that describes a single leg of the path, giving the direction in which to travel expressed as one of the names from the compass rose (`N', `NNE', ...) followed by one or more blanks, then a distance (in stadia) given as a positive floating point number.
All output goes to the standard output stream.
For each successive leg of the journey, print the heading (angle) of beacon A and beacon B on a single line, separated by a single blank. These quantities are to be rounded to the closest degree, and printed in integer format (no decimal points).
After the angles for the final leg, print the phrase `END OF PATH' on a line by itself. Print a blank line between datasets.
3 S 50.0 W 25.0 ESE 10.5
315 45 333 56 327 50 END OF PATH
______________________________________________________ 2115false
Consider the function f which is inductively defined on the positive integers, as follows:
f(1) = 1Given a positive integer value for n (greater than or equal to 1), find the value of f(n).
f(2n) = n
f(2n+1) = f(n) + f(n+1)
2 53 153 1
f(2) = 1 f(53) = 27 f(153) = 77
______________________________________________________ 2116false
The Mobius function M(n) is defined on positive integers as follows:
M(n) = 1 if n is 1.For example:
M(n) = 0 if any prime factor of n is contained in n more than once.
M(n) = (1)^{p} if n is the product of p different prime factors.
M(78) = 1, since 78 = 2 x 3 x 13.Given a value for n greater than or equal to 1 and less than or equal to 10000, find the value of M(n).
M(34) = 1, since 34 = 2 x 17.
M(45) = 0, since 45 = 3 x 3 x 5.
78 34 45 105 1 1
M(78) = 1 M(34) = 1 M(45) = 0 M(105) = 1 M(1) = 1
______________________________________________________ 2117false
A flat rectangular maze is constructed from square cells. Each cell has one, two, or three open sides. The maze has two entry points from outside the maze, one in the cell at the upper left corner of the maze, and the other in the cell at the lower right corner of the maze. A maze may have dead ends, but it does not contain any loops. That is, there is no forward path through a maze that will lead back to a previously visited cell.
At the same time, two robots (named Ro and Bot) enter and begin traversing the maze. Ro enters at the upper left corner, and Bot enters at the lower right corner. Each robot takes the same amount of time to move from one cell to the next. The robots follow these rules in traversing the maze:
If a robot enters a cell that has only one open side (a dead end), the robot turns around and leaves the cell. If a robot enters a cell that has two open sides, it leaves using the side through which it did not enter. If a robot enters a cell that has three open sides A, B and C (labeled in clockwise order), and was first entered through side A, the robot must choose to leave through side B or side C. Ro will choose to exit through side B, and Bot will choose to exit through side C. If a dead end later causes a robot to return to the cell, it will then leave through the last remaining open side. For example, if Ro enters a cell with three open sides through side A, it will leave through side B. If that route leads to dead ends, Ro eventually returns to the cell and leaves through side C. Naturally if all paths reached through sides B and C lead to dead ends, the robot eventually retreats back through side A (which it first used when it entered the cell). The robots stop if they meet in a cell (at the same time) or if they exit the maze. You are to write a program that will determine from the description of a maze if the robots will stop inside the maze, and if they do, the cell at which they will stop.
A few examples will clarify these ideas. Shown below are three mazes. Below each maze is a table showing the cells through which the robots will pass while traversing the maze. Row and column numbers are used to identify the cells in each maze.
A pair of zeroes follows the data for the last case.
The robots do not meet.or the message
The robots meet in row R, column C.as appropriate (with R and C replaced by the row and column number at which the robots meet). Leave a single blank line between the output for each maze.
4 3 A C 4 4 7 D 7 D 1 1 3 A 3 7 C 4 2 E A E C 5 3 E 9 6 9 1 3 A B 8 3 A A 5 4 A E C 4 4 5 1 5 3 B A D 6 C 6 9 1 3 B A 0 0
Maze 1: The robots do not meet. Maze 2: The robots meet in row 1, column 4. Maze 3: The robots do not meet.
______________________________________________________ 2118false
The single player game of minesweeper is played on a rectangular grid. Each cell in this grid is either vacant or contains a mine. When the game begins, all cells are covered so the player cannot tell if a cell contains a mine. Plays consist of selecting and uncovering cells, one at a time. If an uncovered cell contains a mine, the game is over. If the cell does not contain a mine, it reveals an integer that indicates the number of neighboring cells that do contain mines. Neighboring cells are those that are immediately adjacent either horizontally, vertically, or diagonally.
In this problem, you are given a game grid on which some number of plays has already been made without uncovering a mine. You are to determine the status of those still covered cells whose status can be determined using only the information revealed by the uncovered cells. That is, for each cell still covered, determine if its status can be discovered, and if so, whether or not it contains a mine.
As an example, consider the grids shown below. The cells with the darker background color and without a number represent cells that are still covered. The cells containing a number are uncovered, and the number each contains indicates the number of neighboring cells that contain mines. In the left grid, it is clear that the rightmost uncovered cell in the top row contains a mine, as do the last uncovered cell in the leftmost column and the rightmost uncovered cell in the second row from the top. These cells have been marked with an asterisk (*) for clarity. We can now determine that the covered cells marked with a plus sign (+) have no mines. The status of the cell in the upper left corner of the grid cannot be determined. In the right grid, we cannot unambiguously determine the status of any uncovered cells. It could be that the first or second cell in the top row contains a mine, with the other cell not containing a mine.
A pair of zeroes follows the data for the last case.
5 5 1 1 1 1 1 1 1 2 1 1 1 2 1 0 0 1 1 0 0 0 1 1 0 0 0 2 2 1 1 1 1 0 0
Case 1: Cells with mines: (1,4), (2,2), (4,1) Cells without mines: (1,2), (1,3), (2,1), (3,1) Case 2: Cells with mines: Cells without mines:
______________________________________________________ 2119false
A popular television game show requires contestants to identify a phrase, usually with some of the letters missing. Some of these phrases are formed from a combination of two phrases that are unrelated, except that the last word (or words) of the first phrase are the same as the first word (or words) of the second phrase.
For example, consider the phrases the shallow end of the pool and the pool table. The last two words of the first phrase (the pool) are the same as the first two words of the second phrase. These phrases could then be combined to yield the before and after phrase the shallow end of the pool table.
In this problem you are given a set of phrases and asked to find all possible before and after phrases that can be produced. For each such combination, you are to display the two phrases, one per line, with the common words aligned.
The order in which the before and after phrases are displayed should correspond to the order in which the first phrase of the combination appears in the input data.
house of cards the pool table the white house the house limit the shallow end of the pool (This line is blank)
the white house house of cards the shallow end of the pool the pool table
______________________________________________________ 2120false
Prime numbers (those that have only themselves and other primes as factors) starting with 2 can be arranged on a twodimensional plane starting as show below:
Assume a Cartesian coordinate system is used to reference the primes, and that 2 is located at (0,0). We can then see that 3 is located at (1,0), 5 is located at (1,1), 7 is located at (0,1) and 11 is located at (1,1). Given the coordinates of a prime number in this system, find and display the prime number at that location.
1 1 2 2 2 2 999
Case 1: The prime at location (1,1) is 5. Case 2: The prime at location (2,2) is 41. Case 3: The prime at location (2,2) is 59.
______________________________________________________ 2121false
A program is needed to assist in checking and visualizing the mazes for problem 3. In that problem, the input consists of a sequence of maze descriptions. The mazes are rectangular, and consist of a number of square cells. Some of the sides of these cells are solid, and other sides are open.
To be consistent, an open side in one cell must correspond to an open side on the adjacent neighboring cell. The maze characteristics also require that there be only two entry points to the maze, one on the left side of upper left cell in the maze, and one on the right side of the lower right cell in the maze.
These maze characteristics can be easily verified if a visual representation of the maze is available. To prepare such a representation, each cell in the maze is approximately displayed using plus signs at the corners of cells, three hyphens (or minus signs) for a solid top or bottom side, and a single vertical stroke for a solid left or right side. An appropriate number of blanks should be used for any open sides of a cell. If a side shared by two cells is inconsistent (solid in one cell and open in the other), then print three lowercase xs in place of the three hyphens if a top or bottom side is inconsistent, or a single upper case X in place of the vertical stroke if a left or right side is inconsistent.
A cell with solid sides is shown on the left below. To its right a two row, twocolumn maze is shown. This maze has an open side to the left of the upper left cell and to the right of the lower right cell. The visualization also shows an inconsistency between the right side of the upper left cell and the left side of the upper right cell, and an inconsistency between the lower side of the upper right cell and the upper side of the lower right cell.
Display a visual representation of each maze in the input data.
4 3 A C 4 4 3 D 7 D D 1 3 A 3 7 C 4 2 2 A E C 5 3 E 9 6 9 1 3 A B 8 3 A A 5 4 A E C 4 4 5 1 5 2 B A D 6 C 6 9 1 3 B A 0 0
Maze 1: ++++   ++ + +    + +xxx+ +  X  + + +xxx+   ++++ Maze 2: ++++++++   X  + + ++xxx++ + +      + ++ ++ +++   ++++++++ Maze 3: +++++   ++ + + +      +xxx+ ++ +   ++++ +    + + + ++   +++++
______________________________________________________ 2122false
The functional programming language LISP uses sexpressions to represent programs and the data on which they operate. A simplified definition of an sexpression is as follows.
1. Any single alphabetic letter, upper or lower case, is an sexpression.
2. If u and v are sexpressions, then so is (u,v) .
For example, each of the letters a, c and m is individually a legal sexpression, as confirmed by part 1 of the definition. Using part 2 of the definition, we determine that (a,c) is also a legal sexpression, and then so is ((a,c),m).
Your task, in this problem, is to develop a recognizer for sexpressions of the form just described. For each potential sexpression given in the input, you are to determine if it is legal and to display your finding.
a b (a,b) ((a,b),(C,d)) (ab,c) [ a , b ] (This line is blank)
1: a is an sexpression. 2: b is an sexpression. 3: (a,b) is an sexpression. 4: ((a,b),(C,d)) is an sexpression. 5: (ab,c) is not an sexpression. 6: [ a , b ] is not an sexpression.
______________________________________________________ 2123false
The Quadratic Equation was a topic that preoccupied you for some time in Algebra. In this problem you'll be revisiting this topic. You are to find the roots of a quadratic equation:
One way to solve a modular quadratic is to use the good old Quadratic formula. The only caveat is how to perform the operations needed in the quadratic formula (efficiently!). For example, we need:
Modular Power Operation
Modular power is defined by the equation: (a)^{b} (Mod p). You take the exponent of the number a and calculate the result (Mod p):
Examples of Modular Power Operation:
CASE: p = 7:
(5)^{4} 625 2 (Mod p)
CASE: p = 13:
(5)^{4} 625 1 (Mod p)
Modular Square Root Operation
A number n has two square roots (Mod p), if and only if the following condition holds:
CONDITION  IMPLIES THAT 
n^ ((p  1)/2) = = 1 (Mod p)  n has two square roots (Mod p) 
n^ ((p  1)/2)! = 1 (Mod p)  n has no square root (Mod p) 
If n has two ``square roots" (Mod p), then there exists two integers r_{1}, r_{2} such that:
^
2 (Mod p) and n r_{2}^
2 (Mod p)
The main trick is finding the integers r_{1}, r_{2}. While we won't show you how to calculate a ``square root" (Mod p), (that's your job!) we will show you how these square roots work:
Examples of Modular Square Root Operation:
CASE: p = 7:
Given below are the two ``square roots" of 4 (Mod p)
r_{1} = Sqrt(4) 2 (Mod p)
r_{2} = Sqrt(4) 5 (Mod p)
Make sure these are indeed the ``square roots" of 4 (Mod p)
Check r_{1}: (r_{1})^
2 2 * 2 (Mod p) 4 (Mod p) 4 (Mod p)
Check r_{2}: (r_{2})^
2 5 * 5 (Mod p) 25 (Mod p) 4 (Mod p)
CASE: p = 337639277:
Given below are the two ``square roots" of 17 (Mod p)
r_{1} Sqrt(17) 113622037 (Mod p)
r_{2} Sqrt(17) 224017240 (Mod p)
Make sure these are indeed the ``square roots" of 4 (Mod p)
Check r_{1}: (r_{1})^
2 12909967292029369 17 (Mod p)
Check r_{2}: (r_{2})^
2 50183723817217600 17 (Mod p)
Modular Division Operation
In order to do modular division, you need to understand the modular multiplicative inverse operation. Assume that z is the multiplicative inverse of a number b then the following should hold:
Examples of Modular Division:
CASE: p = 7:
Calculate 5/4 5 * (4)^{1} (Mod p)
First, find the inverse of 4 (Mod p): (4)^{1} 2 (Mod p)
Second, calculate 5 * (4)  1 5 * 2 10 3 (Mod p)
Check: (5/4) * 4 3 * 4 12 5 (Mod p)
CASE: p = 13:
Calculate 5/4 5 * (4)^{1} (Mod p)
First, find the inverse of 4 (Mod p): (4)^{1} 10 (Mod p)
Second, calculate 5 * (4)  1 5 * 10 50 11 (Mod p)
Check: (5/4) * 4 11 * 4 44 5 (Mod p)
The Program
!!!NOTE!!!: Calculations may require integers up to a maximum of 64 bits in length.
Your task is to write a program that reads quadratic equations from a text file, and determines whether or not each of the equations in the input has roots (Mod p). Each quadratic equation is on a separate line. The coefficients a, b, c of each quadratic equation and a modulus p are given on each line. You may safely assume that all the nonnegative values of p are odd prime numbers, however, if you encounter a negative p value, you should output the message ``invalid input" as shown below in the sample. Your program must be efficient, because the input file will contain a large number of equations to solve.
For each equation, output the equation and the root(s) in the following format:
Q[x_] := Mod[ ax^
2 + bx + c, p ]
{ root(s) or message goes here }
...blank line...
Q[x_] := Mod[ ax^
2 + bx + c, p ]
{ root(s) or message goes here }
...blank line...
To see how this format corresponds to actual input look at the sample input and output given below.
4 3 3 13 4 3 3 13 17 8 1 71 3 1000 65709 337639 1 179344794 146367396 179424691
Q[x_] := Mod[ 4x^2 + 3x + 3, 13 ] { invalid input } Q[x_] := Mod[ 4x^2 + 3x + 3, 13 ] { 11 } Q[x_] := Mod[ 17x^2 + 8x + 1, 71 ] { has no roots } Q[x_] := Mod[ 3x^2 + 1000x + 65709, 337639 ] { 2345, 109868 } Q[x_] := Mod[ 1x^2 + 179344794x + 146367396, 179424691 ] { 78021, 1876 }
______________________________________________________ 2124false
Given 3 values, s_{1}, s_{2}, s_{3}, what is the smallest integer having a base less than or equal to 36 such that s_{1} + s_{2} = s_{3}? Each string, s_{1}, s_{2}, s_{3}, is composed of digits and upper case letters, with ASCII value ordering (0123...XYZ).
Groups of 3 strings (one per line) s_{1}, s_{2}, s_{3}.
Input will end with a single `0' alone on a line. Thus, the total number of lines will be 3 * k + 1 (for some integer k). There will be no leading zeros.
For each triplet of s_{1}, s_{2} and s_{3}, print one line of output (linewrap is allowable for long strings):
5 3 10 5 3 11 5 3 8 5 3 7 ABC DEF 18AB 1111111111111111111 2222222222222222222 3333333333333333333 0
5 + 3 = 10 in base 8 5 + 3 = 11 in base 7 5 + 3 = 8 in base 9 5 + 3 != 7 ABC + DEF = 18AB in base 16 1111111111111111111 + 2222222222222222222 = 3333333333333333333 in base 4
______________________________________________________ 2125false
Cribbage is an old card game, usually played by 2 people. Points are scored by having various card combinations in a hand. In Cribbage, many of these combinations are similar to other card games, twoofakind, threeofakind, fourofakind and runs (numerically sequential cards of 3 or more). But also in Cribbage, combinations of cards that add up to 15 are important. (Face cards are counted as 10 points, and aces are worth 1 point).
In a standard, twoplayer game, each person is dealt 6 cards. Four of these cards are kept as the player's hand, and the other 2 are placed in the ``crib". The crib is given to each player alternately. Therefore, scoring is done on groups of 4 cards (either in the hand or the crib). In addition, a single card is turned up (after the crib is made), which can be used to supplement the scoring.
In our version of Cribbage, we will be ``dealt" 8 cards, plus the one extra. It is the job of your program to divide the 8 dealt cards into a hand and a crib (4 cards each) such that the maximum total score is achieved, using the extra card as appropriate. (That is, the sum of the hand and the crib is maximized.)
For our purposes, we will not use card suits, and we will represent the cards as single characters,
as follows:
Ace=1, Two=2, Three=3, Four=4, Five=5, Six=6, Seven=7, Eight=8, Nine=9, Ten=T, Jack=J, Queen=Q, King=K
Scoring
Twoofakind (a pair): 2 points
Threeofakind (3 pair): 6 points
Fourofakind (6 pair): 12 points
Runs (sequentially numbered cards of length greater than 2): 1 point per card in the run
Fifteens: 2 points for any distinct combination of cards that sum to 15
Example #1
Hand dealt: 5T524765
Extra card: 9
Best possible total score: 20 points
Explanation:
Hand: 555T = 14 points (3 pair for 6 points, plus 4 15s for 8 points(10+5, 10+5, 10+5, 5+5+5))
Crib: 2467 = 6 points (3 15s (9+6, 2+4+9, 2+6+7))
(Note that either group of 4 could be the ``crib" and either group the ``hand".)
Example #2
Hand dealt: 46K98827
Extra card: 5
Best possible total score: 18 points
Explanation:
Hand: 6788 = 14 points (2 runs of 4 cards for 8 points, a pair of 8s for 2 points, and two 15s (8+7, 8+7) for 4 points)
Crib: 249K = 4 points (2 15s (2+4+9, 5+K))
Example #3
Hand dealt: 76547T61
Extra card: 6
Best possible total score: 25 points
Explanation:
Hand: 4566 = 21 points (3 runs of 3 cards for 9 cards, 3 pair for 6 points, 3 15s for 6 points)
Crib: 177T = 4 points (a pair for 2 points, one 15 (1+7+7) for 2 points)
Note that the extra card is not displayed as a part of either the hand or the crib, but it can be
used in scoring for both.
Your task is to write a program that reads a file of ``dealt" cards, and returns the maximum point total for each dealing, along with the hand and crib configuration that produced that score. (Order of cards in display is ascending. Which group of 4 is the hand and which is the crib is immaterial.)
The input file will consist of a series of lines, each line containing 9 ``cards". The last card on each line will be considered the ``extra" card for that dealing. The last line in the file will consist of 9 zeroes, which will indicate the end of file, and the end of your processing. All input characters will be of a valid card type, as explained above. Cards represented by alphabetic characters will be capitalized. There will be no spaces between card characters, and no blank lines in the file.
Deal #1:
Extra Card: x
Hand: xxxx = yy points
Crib: xxxx = yy points
Best Score = zz
Deal #2:
Extra Card: x
Hand: xxxx = yy points
Crib: xxxx = yy points
Best Score = zz
etc.
Note that a line of whitespace is required between the output for each dealing.
Note also that the explanation of scoring (as seen in the examples) is not to be displayed in the actual program output.
5674JKQ27 Q1Q2Q3Q45 000000000
Deal #1: Extra card: 7 Hand: 4567 = 12 points Crib: 2JQK = 3 points Best Score = 15 Deal #2: Extra card: 5 Hand: QQQQ = 20 points Crib: 1234 = 7 points Best Score = 27
______________________________________________________ 2126false
This problem features a variant of the game of "poker solitaire" (PS). To play PS, deal a 5 x 5 grid of cards from a standard deck. The score for a PS grid is the SUM of the scores for each row, column, and diagonal. These twelve hands each score as follows:
In normal poker solitaire, the player deals one card at a time and can place the card in any open space until all twentyfive are dealt. But we've changed the game! We'll give you a grid of twentyfive cards and then you'll swap pairs of cards to try to maximize the score. At each step, choose the pair of cards that maximizes the score (be greedy).
You'll need to calculate the number of steps until no single step yields improvement.
If there are several possible steps with the same score, break ties by choosing the pair with the lowest POSITIONED card in it, using the following grid:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
For example, swapping 1 & 24 would take priority over swapping 2 & 3. If there's still a tie (for example, 1 & 3 vs. 1 & 5), use the second card's position in the grid, taking the lower one.
The input file will contain a series of 5 x 5 grids of cards. Each line will correspond to a row of five cards. Each card will be a rank (`2'`9', `A', `K', `Q', `J', `T') followed by a suit (`C', `D', `H', `S'). For example, a single row would look like this:
TD 2S 3C AS QH
Each row will be flush to the left and cards will be separated by exactly one blank. Thus there are EXACTLY 14 characters per row.
There will be a row with 14 zeros (``00000000000000") to signal the end of input.
The number of rows will be divisible by 5 (we won't give you a partial grid at the end).
For each grid, print three lines, followed by a blank line, with:
the score for the initial grid
the number of steps
the score for the final grid
AD KD QD JD TD AC TC QC JC KC AS KS QS JS TS AH KH QH JH TH 9S 9C 9D 9H 8S AD KD QD JD TD TC AC QC JC KC AS KS QS JS TS AH KH QH JH TH 9S 9C 9D 9H 8S AC KD TH JD TD TC AD QC JC KC AS KS JS JH TS AH KH QH QH 9D 9S 9C QD 9H 8S 00000000000000
Initial score = 317 Steps = 1 Final score = 357 Initial score = 298 Steps = 2 Final score = 357 Initial score = 38 Steps = 7 Final score = 314
______________________________________________________ 2127false
Before the age of computing, some of the simplest codes were sent in plain view, embedded in a long string of text. The simplest type of this embedded code is to ``hide" a string of text every n characters in the larger block of text. The recipient only needed to know the value of n, to extract the message.
You are to write a program that searches a block of text for a given string. Determine if the string is embedded somewhere, and if so, report the n value.
For example,
String to search for: Hello World
Text to search through: AHaealalaoa aWaoaralad
Result: ``Hello World" is found with encoding of 2.
In this problem, case matters. Treat all characters in the string to search for as significant, including spaces. That is, in the above example, if the text to search through was ``AhaealalaoaaWaoaralad", then ``Hello World" is not found.
The input file for this program will consist of a series of search pairs. The first line of such a pair will be the string to search for (the embedded code). This line will be no more than 80 characters long and will be terminated by the character `*'. The next (up to) 255 characters will be the text to search through. The character `*' will determine the end of this line. Both the search string and the text to search through will be comprised of alphanumeric characters and the space character. There will be no punctuation, carriage return/line feeds or any other whitespace other than the space character contained in either string. (The file, of course, will contain carriage return/line feeds, but these will not be found in either string.) The end of the input file will be denoted by the `#' character. You may assume the text to search through is at least as long as the string being searched for.
For each search pair, output one line of text, either:
[ search string] is not found.
Or
[ search string] is found with encoding of n.
where `` search string" is replaced with the actual string being searched for, and n is replaced with the integer encoding value.
Hello World* AHbecldleof gWhoirjlkd* Hello World* AhbecldleofgWhoirjlkd* DOS RULZ* ZaDerOssS87 poRkjUaaL9lZ* DOS RULZ* ZaDerOsss87 poRkjUaaL9lZ* #
[Hello World] is found with encoding of 2. [Hello World] is not found. [DOS RULZ] is found with encoding of 3. [DOS RULZ] is not found.
______________________________________________________ 2128false
Congratulations! You've just taken a job as an analyst for KACM radio, a station that broadcasts to a region extending over the square from [10,10] to [10,10] inclusive.
KACM has some (one or more) transmitters of varying power, all located at integer coordinates inside the broadcast region. They would like to have their signal strength exceed a constant at every integer coordinate in the zone. The signal strength at a point is just the sum of the signals from all transmitters. This total signal must exceed 100.
The signal at location L from a transmitter T of power P is given by:
That is, signal degrades quadratically in this world.
Sometimes the signal at all points is above the threshold, but usually it isn't. In such cases, KACM wants to know where to build a single new tower with sufficient (but not excess) power to cover the region. Your job is to determine the integer X,Y location and integer power P such that the signal at all locations within the region exceeds 100.
Note that it is possible to place more than one transmitter at a single location. If such is the case, the power for each transmitter is evaluated separately.
A series of transmitter lists. Each list consists of X Y P integer triples. The end of each list is a ``0 0 0" triple, and the series ends with an empty group (i.e., an extra ``0 0 0").
For each transmitter list, your program is to determine the location of the lowestpowered transmitter that can be added to the grid to provide the needed signal strength at all locations on the grid. If more than one location can be used for such a transmitter, select the location with the smallest X coordinate. If more than one location exists with the same X coordinate, select the location with the smallest Y coordinate. Print a line indicating the transmitter power required and selected location using a format similar to that of the sample output. If every location on the grid already receives a signal of adequate strength, print the message ``No additional transmitters needed" on a separate line.
Note: The sum S at any location is guaranteed to be less than 1,000,000 (we're not going to throw a bunch of highpowered transmitters at you and watch your program overflow).
0 0 20000 0 0 0 0 0 10000 0 0 0 5 5 5000 5 5 5000 0 0 0 7 7 1224 7 7 1224 7 7 1224 0 0 0 7 7 2000 7 7 2000 7 7 2000 0 0 0 5 2 1000 7 6 3000 7 5 2000 10 10 300 10 10 5000 10 10 3000 0 0 0 0 0 0
No additional transmitters needed Add a power 10000 transmitter at 0,0 Add a power 6900 transmitter at 0,10 Add a power 9990 transmitter at 3,3 Add a power 6120 transmitter at 4,4 Add a power 169 transmitter at 1,3
______________________________________________________ 2129false
A very colorful oneperson game can be played as follows. First a set of colors is selected then a set of circles is drawn using some or all of the colors, with duplicates possiblethere are at least as many circles as colors. These circles are then connected together in any way by colored arrowsany number of arrows, with any colors, may be used to connect any pair of circles. For example, if we use the four colors R, G, B, and Z and four circles then we could have the following situation:
Three different circles are then picked from the set; two of them have a counter placed inside, while the third is the ``target" circle. A counter may be moved from one circle to another along an arrow (in the correct direction), only if the other counter is not in the circle being moved to, and the color of the arrow is the same as the color of the circle the other counter is in. A counter may be moved several times in succession  they don't have to be moved alternately. The aim is to get one of the counters in the target circle, in the least number of moves; if the target circle can't be reached, the game is ``impossible".
For example, in the picture above, if one counter is in the B circle, the other counter is in the Z circle, and the target is the G circle, then the game can only be won by moving the Z counter to the R circle (since a B arrow runs in that direction), which makes it possible to move the B counter to the Z circle along the R arrow, and the R counter can now be moved to the G circle along the Z arrow, for a total of three moves.
Input will be from a text file and will consist of descriptions of several games, using numbers instead of colors. The first line of each game description contains five numbers, N, R, S, T, M where N is the number of circles in the game (they will be numbered 1 to N, with N100), R and S are the numbers of the circles the two counters start in, T is the number of the target circle, and M is the total number of arrows connecting the circles (M5, 000). After this are several lines (maximum length 60 characters) containing N numbers giving the colors of the circles in order (1 to N), with up to 20 numbers per line, separated by one or more spaces. The colors are denoted by numbers from 1 to N  some of these numbers may be unused. Then come M lines which define the arrows, in no particular order. Each contains three numbers; the first is the number of the starting circle, the second the number of the ending circle, and the third is the color of the line. The input will be terminated by a line consisting of a five zeroes. The first example below describes the picture above.
Output, which must be written to standard output (the screen), must be one number for each game description giving the minimum number of moves to complete the game, or 0 if the game is impossible.
4 2 3 4 7 1 2 3 4 1 4 3 1 4 4 2 3 1 3 1 2 4 2 3 4 3 2 4 3 1 5 3 4 1 8 2 3 2 1 4 2 1 2 4 1 5 4 5 3 5 1 4 3 2 1 3 2 2 5 3 3 3 5 1 0 0 0 0 0
3 4
______________________________________________________ 2130false
Your competitors in the low end routing business are adding firewall type features and your sales department is frantic. They want to add access lists ASAP.
But the marketeers also require that `wire speed' routing not be compromised and the routing engine is underpowered. Your job is to write a simulator to help answer the performance questions.
Engineering has used a sniffer to record network traffic and extracted the relevant information from the packet headers.
Here are some samples of the simulated traffic packets:
216.35.137.204 0 131.215.211.5 0 1 131.215.139.100 49152 131.215.90.109 53 17 24.218.179.217 27015 131.215.89.4 2326 17 148.246.129.175 6699 131.215.142.85 1138 6
The fields are:
source IP address  source port  destination IP address  destination port  protocol 
dotted decimal address  decimal number  dotted decimal address  decimal number  decimal number 
The fields are separated by one or more blanks and the first field may be preceded by one or more
blanks.
A dotted decimal address is a 32 bit value, high order byte first, with the decimal representation of each 8bit byte (0..255) separated by a `.' (decimal point). For example, 1.2.255.15 is 0x0102FF0F.
Ports are in the range: 0..65535
Note that ports are only significant for the TCP (6) and UDP (17) protocols. The port fields will be
0 for other protocols.
The protocol is in the range: 0..255
You will be given sample access lists. They will be syntax checked with fields that are separated by
one or more blanks. Some example entries:
* 1.2.3.4 255.255.0.15 3 5.6.7.8 0.0.255.255 9 Permit 6 0.0.0.0 0.0.0.0 * 131.215.254.254 255.255.255.255 21 deny
The fields are:
protocol  source IP  source  source  destinatio  destinatio  destinatio  action 
address  mask  port  n IP  n mask  n port  
address  
decimal  dotted  dotted  decimal  dotted  dotted  decimal  ``permit' or 
number or  decimal  decimal  number or  decimal  decimal  number or  ``deny' (case 
`*'  address  mask  `*' or a  address  mask  `*' or a  not 
range  range  significant) 
A range is two decimal numbers separated by `' with no whitespace between the numbers and the `'. For example, 552 will match any port number between 5 and 52.
In the access list, the protocol and the ports can be specified as `*', which means match any protocol or port.
A dotted decimal mask is the same format as an address. It indicates which bits are significant when comparing addresses. For example, the addresses 123.234.248.14 and 123.234.254.126 match when compared with the mask 255.255.240.15 (0xFFFFF00F). The 1 bits in the mask show which bits in the addresses to compare. Note that a mask of 0.0.0.0 will cause any address pair to match.
The way an access list works is each simulated traffic packet is compared with the access list entries, in the same order those entries were provided, until the packet matches an entry. For a match to occur, the protocol, source and destination addresses (using the respective masks), and ports must all match. In a real router, the action directs the router to accept or reject the packet, but the simulator just keeps track of how many access list entries are compared, and the number of times each action is taken.
For example, if a packet matches the 3rd, 5th, and 8th entries in a 30 entry access list, (with the action of the 3rd entry being `permit'), then processing that packet will contribute 3 comparisons and add 1 to the number of `permit' actions taken. In this case the 5th and 8th entries are not examined further. The first entry that matches is the last examined for a given packet.
The input file will be a series of test cases. Each test case consists of two groups of data, separated by a blank line. A blank line also separates test cases. The first group of data in a test case is the access list entries, one per line. There will be no more than 100 access list entries. The next group of data in the test case is the simulated packet traffic data. Each of these lines will be at most 100 characters. The test case is terminated by a blank line or endoffile.
For each test case print 3 numbers: the total count of access list entries compared; the number of simulated packets resulting in the `permit' action; and the number of simulated packets resulting in the `deny' action. Put no leading spaces before the first number and exactly 1 space before the 2nd and 3rd numbers.
* 204.69.0.0 255.255.248.0 * 0.0.0.0 0.0.0.0 * permit * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * DENY 204.69.6.230 3072 24.115.85.245 23 6 192.168.215.17 53 204.248.52.7 1243 17 204.69.12.21 2118 152.163.241.11 21 6 * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * deny 192.102.199.19 27961 63.20.61.96 65535 17 6 198.138.176.100 255.255.255.255 * 204.69.4.100 255.255.255.255 111 permit 6 0.0.0.0 0.0.0.0 * 204.69.0.0 255.255.240.0 111 deny 6 0.0.0.0 0.0.0.0 * 204.69.0.0 255.255.248.0 80 permit * 0.0.0.0 0.0.0.0 * 204.69.0.255 255.255.248.255 * deny * 204.69.0.0 255.255.248.0 * 0.0.0.0 0.0.0.0 * deny * 127.0.0.0 255.0.0.0 * 0.0.0.0 0.0.0.0 * deny * 0.0.0.0 0.0.0.0 * 204.69.7.240 255.255.255.240 99909999 deny * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * permit 204.69.4.87 80 204.69.9.12 6776 6 134.79.112.65 2186 204.69.4.218 21 6 216.112.217.140 2212 204.69.5.255 22 6 198.138.176.100 1053 204.69.4.100 111 6 198.138.176.100 1054 204.69.5.100 111 6
5 1 2 1 0 1 20 2 3______________________________________________________ 2131false
You have recently landed a job with an supercomputing application hosting firm. The firm's primary mission is to provide distributed computing for its customers across its networked supercomputer. The supercomputer consists of many individual computers of varying size (i.e. Mainframes, Servers, and Workstations) and configurations (i.e. OS's, hardware, MIPS). Each of these computers are commonly referred to as processing nodes. Customers submit to a centralized distribution point the programs they want executed and the sets of data files to be processed. Each program is distributed to the processing nodes along with a particular data file. The program is then executed on each node with general security privileges. The types of programs that customers submit are thread intensive, utilize a large amount of interprocess communication, and execute generic OS system calls. The results of the processing are then communicated to the submitter.
The firm's customers are primarily competing bioengineering firms researching the human genome. Each is racing to patent particular genes and gene interactions which they discover. Since the applications are submitted directly by the customers and many customers will be submitting programs for distributed computation at the same time, security of the processing nodes and of individual customer data and source code is of paramount importance.
Your project lead is concerned that some customers may try to interject virus or malicious code into the distribution process, either to crash the processing nodes, steal the source code and data of other customers, or affect the programs of other customers in order to produce erroneous data.
You have been tasked with writing a malicious code scanning program for the distribution subsystem. Its primary functional requirement is to scan programs and data files submitted by customers and compare them to the malicious code library your company maintains. This program will produce reports indicating if malicious code exists in the submitted program and data files.
Here are a the requirements given to you by your lead:
Input will consist of up to 100 data sets. Each data set will be correct and follow the following rules:
Elements of a  Description  Example 
Malicious code  
description  
Malicious code signatures start line  A set of characters of the form MALICIOUS CODE SIGNATURES followed by a new line character.  MALICIOUS CODE SIGNATURES 
Any number of Code Signatures  Next bullet in the list 
Elements of a  Description  Example 
Signature  
Signature description start line  A set of characters of the form < x > (any combination of the following valid characters ``a"..``z", ``A"..``Z", ``0"..``9", & ``.") followed by a name of the signature.  RABBIT 
Threshold percentage start line  A set of characters of the form THRESHOLD PERCENTAGE followed by a new line character.  PERCENTAGE THRESHOLD 
Threshold percentage  A set of characters of the form < y > (any combination of the following valid characters ``0"..``9" & ``.") followed by a new line character. <y> is the threshold percentage to 2 decimal places of precision i.e. 100.00, 95.03 etc.  50.00 
Threshold percentage end line  A set of characters of the form THRESHOLD PERCENTAGE followed by a new line character.  THRESHOLD SIGNATURE 
Code Signature start line  A set of characters of the form SIGNATURE followed by a new line character.  
Code signature  A set of characters (1..n  all ASCII characters except EOF and EOLN are valid) followed by a new line character. The entire contents of these lines is the code signature.  We 
Code Signature end line  A set of characters of the form SIGNATURE followed by a new line character.  SIGNATURE 
Signature description end line  A set of characters of the form SIGNATURE followed by a new line character.  RABBIT 
Elements of a  Description  Example 
Malicious code  
description  
Malicious code signatures start line  A set of characters of the form MALICIOUS CODE SIGNATURES followed by a new line character.  MALICIOUS CODE SIGNATURES 
Elements  Description  Example 
of code file  
to scan  
File start line  A set of characters of the form < z > (any combination of the following valid characters ``a"..``z", ``A"..``Z", ``0"..``9", & ".") followed by a new line character. < z > is the name of the file.  XCHROMOSOMECALC1 
Data start line  A set of characters of the form DATA followed by a new line character.  DATA 
Data  characters (1...n  all ASCII characters except EOF are valid) followed by a new line character. The entire contents of these lines is the data or program file to be scanned. 
Class calc {
public calc() {
Wefg6me3to 632edcM
regsdfal p3455agdisg fogiest.
System.out.println("cmo");
While heM; egimm;
ing; System
.out.println("con
\ntest");
}
} 
Data end line  A set of characters of the form DATA followed by a new line character.  DATA 
File end line  A set of characters of the form < z > (any combination of the following valid characters ``a"..``z", ``A"..``Z", ``0"..``9", & ``.") followed by a new line character. < z > is the name of the file.  XCHROMOSOMECALC1 
For each data set, output will consist of a set of characters of the form ``< z > < r >" where < z > is the name of the data file which was scanned (any combination of the following valid characters ``a"..``z", ``A"..``Z", ``0"..``9", & ``.") and < r > is a set of characters of the form ``CLEAN" or ``POISON" followed by a new line character. ``CLEAN" indicates the file does not contain any malicious code matches equaling or exceeding the threshold percentage for any signature. ``POISON" indicates that the file does contain malicious code matches exceeding the threshold percentage for at least one signature.
MALICIOUS CODE SIGNATURES MALICIOUS CODE SIGNATURES XCHROMOSOMECALC1 DATA Class calc { public calc() { Wefg6me3to 632edcM regsdfal p3455agdisg fogiest. System.out.println("cmo"); While heM; egimm; ing; System .out.println("con\ntest"); } } DATA XCHROMOSOMECALC1 MALICIOUS CODE SIGNATURES RABBIT THRESHOLD PERCENTAGE 50.00 THRESHOLD PERCENTAGE SIGNATURE We SIGNATURE RABBIT MALICIOUS CODE SIGNATURES XCHROMOSOMECALC1 DATA Class calc { public calc() { Wefg6me3to 632edcM regsdfal p3455agdisg fogiest. System.out.println("cmo"); While heM; egimm; ing; System .out.println("con\ntest"); } } DATA XCHROMOSOMECALC1 MALICIOUS CODE SIGNATURES RABBIT THRESHOLD PERCENTAGE 70.00 THRESHOLD PERCENTAGE SIGNATURE Welcome to the ACM regional programming contest. SIGNATURE RABBIT FROG THRESHOLD PERCENTAGE 85.05 THRESHOLD PERCENTAGE SIGNATURE Thats the way uhhu uhhu I like it.. SIGNATURE FROG MALICIOUS CODE SIGNATURES PROTEINFOLDING.2 DATA Public Class { format c: Thats the ACM regional hu I like it.. } DATA PROTEINFOLDING.2
XCHROMOSOMECALC1 CLEAN XCHROMOSOMECALC1 POISON PROTEINFOLDING.2 CLEAN
______________________________________________________ 2132false
A LSU physics researcher who we will call ``Sparky" was very successful in procuring funding for the physics department because of his breakthrough research into new 3dimensional crystalline storage technology. Though a brilliant physicist, Sparky's organizational habits were lacking. His office was strewn with stacks of crystal pictures, and most were not labeled in any way other than to note the orientation of the crystal.
Unfortunately for the physics department, Sparky asphyxiated from laughter after a night grading midterms for his Physics For NonMajors class. You are the lucky new nontenured professor that has been hired by the Physics departement to decipher Sparky's research and keep that grant money flowing.
In Sparky's now vacant office, there is a mess of picutures all about. You know that he was taking three pictures of each crystal he grew (one picture down each primary axis: X,Y,Z). You also know that the crystals grew in a liquid suspension and therefore don't necessarily consist of a single continuous mass.
As a first step in organizing the mess you decide to take the pictures three at a time (one down each axis) and see whether or not they could be pictures of the same crystal. Of course, you know Sparky always took pictures of cubical areas, so you pick out pictures of the same dimensions before examining them.
Here are some other useful things that you know about the pictures:
Input to this problem will consist of a (nonempty) series of up to 100 data sets. Each data set will be formatted according to the following description, and there will be no blank lines separating data sets.
A single data set has five components:
START 5
For each data set, there will be exactly one line of output. This line will simply be the word ``YES" or the word ``NO" (all caps with no whitespace leading or following).
A ``YES" line will appear only if there exists some solid 3dimensional object that could project the given silhouettes. (In other words, these could all be pictures of the same crystal).
A ``NO" line will be output for all data sets that fail to meet the criteria for a ``YES" line.
START 1 O O O END START 3 XXX XOX XOX XXX XXX XXX XXX XXX XXX END START 7 XXXXXXX XXXXXXX XXXXXXX XXXXXXX XXXXXXX XXXXXXX XXXXXXX OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO XOOOOOO OXOOOOO OOXOOOO OOOXOOO OOOOXOO OOOOOXO OOOOOOX END
NO YES NO
______________________________________________________ 2133false
After numerous recounts of the presidential votes in Florida, candidates George W. Bush (Republican) and Al Gore (Democrat) are unconvinced of the accuracy of the results. Each candidate is convinced that he should receive Florida's electoral votes needed to win the presidency and no amount of recounting the ballots will determine a clear winner. Also, it was revealed that some of the volunteers forgot to turn in several ballot boxes, and are currently unavailable on vacation at Disney World.
The U.S. population is justly demanding a resolution to the problem to avoid a third term under Clinton. Political analysts insist that they can determine which candidate the state will be awarded to, based on the income levels of its districts' residents. Jeb Bush, the governor of Florida, has asked you to write a program that will determine which candidate will win Florida, and ultimately the election. The future of the country rests in your hands.
The program will be based on the electoral college system, extended to the district level. Each district is worth a certain number of electoral votes, with the winner of the district determined by the median income of its residents. Exit polls have revealed that if the median income of the district is greater than a certain level, it will be awarded to the Republican candidate. A simple majority of electoral votes is needed to win the entire state (a tie will result in the deciding vote being cast by Jeb, resulting in a Republican victory).
Input will consist of a nonzero number of independent data sets containing election information. Each election data set will conform to the following:
There will be no blank lines in the input, but there will be an endline just before the end of the input.
The output will be the results of the elections from the input. For a given election set, the output will consist of a line containg the winning candidates' name and his number of electoral votes, separated by a comma (there will be no spaces on either side of the comma):
George W. Bush,96
There will be no blank lines separating output sets.
START Al Gore George W. Bush 12 39000 North,50000,10 Northnortheast,30000,18 Northeast,40000,11 East,40000,15 Southeast,43000,13 Southsoutheast,52000,14 South,47000,9 Southsouthwest,25000,20 Southwest,25000,24 West,60000,12 Northwest,39000,11 Northnorthwest,35000,12 END START Bleed N. Hart Pub Lee Kahn 437000 North,25000,40 East,35000,20 South,40000,30 West,45000,20 END
Al Gore,85 Bleed N. Hart,60
______________________________________________________ 2134false
James recently purchased a new palmtop computer at a discount store. To get a really good price, he decided to have the free operating system, "JameSIX", installed instead of the more popular and expensive "Windwoes" operating system. One drawback to the free OS is that there are many bugs, but James is a savvy computer programmer and thinks it worth the risk.
A few days later, James is attempting to play "Sweeper" when all of a sudden the screen flashes and some strange output appears. Angered by this interruption to his favorite game, James decides to use his vast programming knowledge and attempt to debug the program in the free debugger, JDB.
James has found a suspicious piece of code. He knows the values of all variables, and he is attempting to determine if the code fragment was the one that produced the output that interrupted his highscore attempt.
The "JameSIX" Assembly language in which the program was written has a very simple set of commands:
Command  Explanation 
START < progname >  The first statement of a program, where < progname > is the program's integer identifier Example: START 21 
SET < x > < value >  Will set variable < x >'s value to < value > Example: SET a 9 is equivalent to a = 9 Note: < x > < y > can only be integers. 
STORE < x > < y >  Will set variable < x >'s value to the value of variable < y > Example: STORE b a is equivalent to b = a 
MULT < x > < y >  Equivalent to variable < x > = variable < x > * variable < y > Example: MULT b a is equivalent to b = b * a 
SUB < x > < y >  Equivalent to variable < x > = variable < x >  variable < y > Example: SUB b c is equivalent to b = b  c 
DIV < x > < y >  Equivalent to variable < x > = floor(variable < x > / variable < y >) except in the case where variable < y >'s value is 0. If variable < y >'s value is equal to 0, then the statement has no effect on the value of variable < x > or variable < y > or any other variable within the program (i.e. < x > = < x >). Example: DIV b c is equivalent to b = b  c 
ADD < x > < y >  Equivalent to variable < x > = variable < x > + variable < y > Example: ADD b c is equivalent to b = b + c 
PRINT < x >  Prints the value of the variable < x > followed by a carriagereturn Example: PRINT b 
GOTO < n >  Execution moves to the nth line of the program. The first line is line number 1. Example: GOTO 10 
END  This statement ends the current program. Example: END 
And one conditional command (nonsimple):
Command  Explanation 
IF < x > IS < value > THEN < simple >  Where < simple > is any of the previously mentioned simple commands. < simple > is only executed if the value of the variable < x > is equivalent to the integer < value > (this is not a variable). Example: IF b IS 3 THEN ADD b c is equivalent to if b = 3 then b = b + c endif 
NOTE: All variables are of type integer.
Input will consist of a nonzero number of `programs', each of which are completely independent of one another. Each program will conform to the following:
Arguments to individual statements will always be separated by exactly one space, and there will not be any blank lines in the input file.
The output will be the results of the programs in the input file. For a given program, you will print to the output file:
There will be no blank lines separating output sets.
START 1 SET b 10 PRINT b END START 2 SET b 10 SET a 1 SET c 0 STORE c a MULT c b PRINT c END START 10 SET a 1 SET b 2 SET c 3 SET d 4 SET e 5 STORE e a ADD a a PRINT a MULT c b IF e IS 8 GOTO 13 GOTO 7 PRINT c END
START 1 10 START 2 10 START 10 2 4 8 16 48
______________________________________________________ 2135false
Once upon a time there lived a programmer with the potential to be the best Java programmer the world had ever seen, and his name was Sebastian. Unfortunately for Sebastian, he was born several decades prematurely and was forced to store all of his programs on punchcards. If you do not know what a punchcard is ask one of your professors after the contest. We are sure she will be able to tell you many horror stories about punchcards and shoe boxes.
One day Sebastian had to turn in his senior project, a program that calculated pi to a billion decimal places. On his way to deliver his program to the grader, he was suddenly overtaken by a vicious case of scurvy (pizza just doesn't have that much vitamin C). In his mad dash to the nearest lavatory, he dropped the box of punchcards containing his program, and the cards scattered everywhere.
After he had picked up all the cards, and counted them, he realized that one was missing. Luckily Sebastian had taken the time to record his program cardbycard in a notebook at the dorm. This will allow him to replicate the missing card and still turn his project in on time. The problem was that the cards were all jumbled and he didn't know which card to replicate.
Here are a few things that Sebastian knows about his cards:
Please write a program to help Sebastian determine what card number his needs to replicate so that he can turnin his project on time.
Input will consist of up to 100 data sets. Each data set will consist of:
For each data set, output will consist of a single number on its own line representing the card that was missing from the Card list of that data set.
Note: these samples are VERY small compared to some of the data sets your problem will be judged against and are abbreviated due to the number of trees that would have to be destroyed to provide a large example. The limit is 10,000 cards per data set.
START 1 END START 5 1 2 4 5 END START 20 13 14 17 1 2 3 4 15 16 5 18 20 6 10 11 12 7 8 9 END
1 3 19
______________________________________________________ 2136false
My Uncle Lester is known throughout Lafayette Parish as the luckiest man around. He has picked the winners of the last 7 NCAA Basketball Championships. During Mardi Gras last year, I got Uncle Lester to explain exactly how he is able to consistently pick the winners of this event. He is convinced that if you rate teams' offense and defense on a scale of 1 to 10 and then multiply their offensive rating by 5 and subtract double their opponents defensive rating, you will have calculated that teams score if that team played their opponent. (Keep in mind that if a score is not an integer, then that score will be rounded to the nearest whole number.) I told Uncle Lester that this could result in negative scores and he told me that was true, but the eventual outcome is accurate. Whoever has the greatest score will win the game and continue on to the next round.
The result of team A playing team B is calculated as follows:
Team  Offensive  Defensive 
A  w  x 
B  y  z 
Score of team
A = 5*w  2*z
Score of team B = 5*y  2*x
If one team beats the other team by more than 10 points, the winning team's offensive rating will increase by .5. A tie score will result in the winner being the team with the mascot name which would appear first in alphabetical order between the two teams.
As you may know, the NCAA seeds all teams in the tournament. They seed the teams according to their offensive rating. The higher the offensive rating is, the lower the seed is. If more than 1 team has the same offensive rating, then the school mascot names are sorted in alphabetical order with the first team in the list getting the next lowest seed number available. For example, if in determining seed 3, a team with mascot name Bananas has the same offensive rating as a team with mascot name Mangoes then Bananas would be awarded seed 3 position. The tournament bracket is laid out where the highest seeded team plays the lowest seeded team, the second highest seeded team plays the second lowest seeded team, and so on. The winner of the first two games play each other and so on.
1 Team 1 Winner1 16 Team 2  Winner9 2 Team 3      Winner2    15 Team 4 Winner13 3 Team 5   Winner3       14 Team 6 Winner10  4 Team 7   Winner4    13 Team 8 Winner15 5 Team 9  Winner5     12 Team 10 Winner11  6 Team 11    Winner6      11 Team 12 Winner14 7 Team 13  Winner7     10 Team 14 Winner12 8 Team 15  Winner8 9 Team 16
With all of Uncle Lester's theories, and the NCAA's rules for tournament seeding, who will win the next NCAA Basketball Championship, and what will the final score be?
Input will consist of n data sets in the following format:
The output will be the name of the tournament champion and the score of the final game followed by a new line. The final score will be the two scores separated by a minus sign. The champion's score will be first in the sequence.
16 LOU,Snorks,7,8 LSU,Tigers,9,6 OU,Sooners,6,7 TAM,Aggies,4,9 UT,Longhorns,8,3 BU,Cubs,4,4 ACM,Hackers,8,4 IEEE,Techs,7,7 MIA,Soldiers,3,3 MIB,Aliens,6,9 TUG,Warriors,3,8 TNG,Trekkies,4,4 CIA,Agents,5,7 FBI,Gmen,6,6 WWF,Wrestlers,3,5 MAY,Flowers,2,5 4 IBM,Judges,5,5 UPS,Drivers,7,3 TKO,Fighters,8,4 YMCA,Villagers,7,4
LSU 3426 TKO 3527
______________________________________________________ 2137false
The Dominion War has ended and Benjamin Sisco has convinced the Wormhole Aliens to allow the Federation unlimited access to the wormhole that connects Alpha Quadrent and Delta Quadrent. In his discussions with the aliens, Sisco learned that there are other Wormholes that exist throughout the galaxy. He has also convinced the aliens to identify the locations of these wormholes and allow the Federation access to them.
The galaxy has now been fully mapped, and The Federation has determined that a new navigational system needs to be built to take advantage of the new charts. Of particular interest to The Federation is how long a particular trip will take. Your team has been tasked with writing that part of navigational system.
The map of the galaxy is 2dimensional and has been split up into a regular grid of sectors. The first sector is sector 1. Sectors are numbered left to right, bottom to top. It takes one day to travel from one sector to another. It also takes one day to travel through a wormhole from one sector to another. Travel can take place by three types of moves, each of which uses one day:
You can not travel to sectors diagonally.
Your specific task will be to construct a system that can determine the minimum number of days it will take to get from a specified starting sector to a specified target sector.
The input will consist of a nonempty series of input sets. Each input set will follow the following format:
< Sizeofthegalaxy >
< WormholeName >, < Wormhole endpoint #1 >, < Wormhole endpoint #2 >
.
.
.
Trip, < Sector the trip begins in >, < Sector the trip ends in >
The size of the galaxy is in the format < Number1 >x< Number2 >. Number1 and Number2 may be equal, but they do not have to be equal. Number1 represents the number of rows, Number2 represents the number of columns. Both Number1 and Number2 will be greater than 0 and less than or equal to 100.
The list of Wormholes is of variable length (020 wormholes). Wormholes can be traversed in either direction. < WormholeName > may contain alphanumeric characters as well as spaces and underscores.
The single Trip line of the input set specifies the start and end sectors for the trip that the system should chart a course for.
All commas in the input are followed by exactly one space.
Each input set will be separated from the next with a single blank line. There will not be a blank line at the beginning of the input, but there will be an endline just before the end of input.
Note: The below corresponds to the first example in the sample data. Wormholes exist such that you can travel from 3 to 5 and from 42 to 51.
91  92  93  94  95  96  97  98  99  100 
81  82  83  84  85  86  87  88  89  90 
71  72  73  74  75  76  77  78  79  80 
61  62  63  64  65  66  67  68  69  70 
51  52  53  54  55  56  57  58  59  60 
41  42  43  44  45  46  47  48  49  50 
31  32  33  34  35  36  37  38  39  40 
21  22  23  24  25  26  27  28  29  30 
11  12  13  14  15  16  17  18  19  20 
1  2  3  4  5  6  7  8  9  10 
For each input set, there will be a single line in the output. This line will indicate the minimum number of days (0) it will take to get from the starting sector to the ending sector and will have the following format:
Trip from < start sector > to < end sector > takes < days > days
10x10 Wormhole1, 3, 5 Wormhole2, 21, 50 Wormhole3, 90, 100 Trip, 1, 49 100x100 The OSU Wormhole, 1, 5 The OU Wormhole, 39, 2005 The LSU Wormhole, 3021, 9765 The ULLA Wormhole, 50, 2005 The Baylor Wormhole, 2205, 3001 Trip, 45, 3021 100x10 The quick trip, 56, 67 Trip, 55, 67
Trip from 1 to 49 takes 4 days Trip from 45 to 3021 takes 29 days Trip from 55 to 67 takes 2 days
______________________________________________________ 2138false
Uncle Jacques has purchased some colorful floor panels for the dance floor of his club. Every Friday his employees will rearrange the panels so that the disco dance floor will have a new and exciting look. He has purchased a large supply of panels with seven different shapes. Each panel consists of four 1 foot squares as depicted below:
_ _ _ _ _ _       _   _  _ _ _    _ _   _ _   _     _ _ _ _ _ _ _ _ _ _ 1 2 3 4 5 6 7
Uncle Jacques needs to know if his dance floor can be completely covered using these panels. He also needs to know how many different patterns his employees can create on the dance floor. The panels can be rotated in 90degree increments, they cannot overlap, they cannot extend past the edge of the dance floor, and they must cover the dance floor completely.
Your first job is to determine whether the dance floor can be completely covered. Your second job is to determine the number of different patterns that can be created by rearranging the panels. Patterns are considered distinct if the borders between panels are different. For example, for a 4 foot by 2 foot dance floor, there are 4 distinct patterns:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _  _ _   _ _  _ _ _ _    _ _ __ __ _ _ _ _ _ _ _ __ _
Rotations of patterns are also considered distinct. For example, the following four patterns are distinct:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _  __   _ _  _ _ _ _  _ _      _         _ __ __  _ _   _ _   _ _  _ _ _ _ _ _ __ _ __ _ __ _ _
Your program must accept the length and width of the dance floor in feet. There can be any number of dance floor measurements in the input. The dance floor will not be larger than 36 square feet.
There will only be one line of output for each set or measurements. Your program must return the number of distinct patterns, which completely cover the dance floor. If the floor cannot be completely covered, your program must return zero.
2 4 3 3 3 4 4 4
4 0 23 117 ______________________________________________________ 2139falseSwamp County Electronics is a leading supplier of militarygrade widgets, and has been using Statistical Process Control for years to help monitor and control its widget manufacturing process. Statisical Process Control, or SPC, is a discipline that uses sampled and measured products, statistics, and historical sample data to determine if a manufacturing process is either in control or out of control.
Swamp County Electronics (SCE) uses control charts to detect when its product (hence its process) goes out of control: at the end of each hour of production, five units are removed from the assembly line for measurement. Statistics calls the taking of one or more measurements for a single statistical analysis a sample, usually denoted X. Testing the widgets is very complicated; only two units can be tested per hour. The testing apparatus is outrageously expensive and SCE can afford only one such apparatus. As such, at the end of the eight hour workday, the Quality Assurance Team works into the wee hours of the morning, measuring all the units in each sample. As soon as each sample is measured, the sample mean, , and the sample range, R, are calculated:
= x_{i} R = max(X)  min(X)where x_{i} represents each individual measurement. and R are then plotted consecutively on an X&R control chart as in Figure 1. The centerlines, and , are the process targets determined previously by more indepth analyses. The control limits are set at 3s, where s is the expected standard deviation for the process, again determined previously.Figure 1. X&R chart from the sample input.When one of more of the outofcontrol patterns in Figures 2a through 2e are detected on either of the X or R control charts, production is stopped until the cause of the irregularity is fixed, and all of the units manufactured since the onset of the irregularity are discarded. The problem is that the irregular patterns can take up to ten hours to detect, and may not be detected until two days after the onset of the problem.
Before investing in two more test apparatuses to detect irregularities in ``real time," SCE wishes to investigate the use of precontrol charts. Precontrol charts require only two measurements per sample, and these measurements are plotted with respect to the specified product tolerances (upper and lower limits) and precontrol, or PC, lines. PC lines are set at and of the total specified tolerance range. See Figure 3. The precontrol chart is divided into red, yellow, and green zones, with the red zone outside the tolerance limits, yellow between the PC line and the nearest tolerance limit, and green between the PC lines. Green is defined by the closed interval [0:25; 0:75] of the tolerance range, yellow by the halfopened intervals [0; 0:25) and (0:75; 1] of the tolerance range. If either measurement falls in a red zone, or both measurements fall into yellow zones, the process is probably out of control. Compared to X&R charts, the precontrol charts have a higher probability of signaling a problem incorrectly (a false positive), or failing to detect a problem even if it exists (false negative).
Figure 2. Out of control sequences for X or R.Figure 2a: a single point outside of 3s. Figure 2b: seven successive points on one side of the centerline; a point on the centerline cancels the sequence. Figure 2c: two successive points in [3s; 2s) or (+2s; +3s]. Figure 2d: exactly 10 out of 11 successive points on one side of the centerline; a point on the centerline cancels the sequence. Figure 2e: a trend of seven successive points upward or downward (a point followed by six monotonically increasing or decreasing points).
Figure 3. Precontrol chart from the sample input.As a precursor to a costbenefit analysis, SCE has contracted your team to simulate the precontrol chart's effectiveness compared to the X&R chart's trusted behavior. You will use the historical sample data from the control charts. From this data you will compute sample means and ranges for control chart analysis. Then, using only the first two measurements of each sample, you will apply the precontrol chart criteria (red, yellow, green zones), indicating when a false positive or false negative occurs with respect to the outofcontrol patterns depicted in Figures 2a through 2e. Bear in mind that the control chart method is a seriesbased indicatorwhen an irregularity is detected at the end of a sequence, the irregularity actually started at the beginning of the sequence. The precontrol chart indicates ``instantaneous" behavior. A precontrol false positive occurs when there are no irregular control chart sequences overlaying its sample, and occurs at the instantaneous sample. A precontrol false negative really doesn't exist at a particular sample; rather it is the lack of any precontrol problem indication over the duration of a control chart outofcontrol sequence. A false negative is reported at the end of a control chart irregular sequence.
Input
Input to your program consists of two lines of quality specifications: the first line contains the process mean, , and upper and lower control limits. The upper and lower control limits are always centered about . The second line contains the range average, , and its upper and lower control limits, centered about . The third line contains the upper and lower product tolerances. Each remaining line until endoffile holds the data for a fivemeasurement sample. All measurements fall within the range [1000,1000]. Only the values measured may be viewed by your team; what the actual data signifies is highly classified due to the military nature of the production contract. All values within lines are separated by whitespace. The samples are numbered implicitly: line 4 is sample 1, line 5 is sample 2, etc.
Output
Output is a list of false positive or false negative indications along with the sample number where they occurred, one indication per line. In either case, output the sample number without any leading spaces. For a false positive, follow the sample number with the string ``false positive". For a false negative, follow the sample number with the string ``problem missed". The output must appear in ascending order of sample number.
Sample Input
60.5 63.5 57.5 5.5 9.5 1.5 65 55 54 61 59.5 56 56.5 63 57 57 57.1 55.9 58 59 58 59 58.5 57 57.5 63 62.5 59.1 57 57.4 63 62.5 59.2 65 61 56 61.5 62 64 61 58 60 62 59 61 58.5 60 61.5 61 59 58.5 60.5 59 58.5 59 61 58.5 58 56 58 58 62.3 58 58 60 57 56 57 58 56 59 62.3 58 60 62 56 61.5 66 60 62 56.5 61.5 65.5Sample Output
2 false positive 3 problem missed 5 false positive 12 problem missed 14 problem missed______________________________________________________ 2140false
Satellite imagery that was collected worldwide is being reformatted into a latitude/longitude coordinate system in order to produce a map. The data is being divided into square cells for layout onto a grid. The map grid extends completely around the world in the longitudinal (westeast) direction but does not extend to either the North or the South Poles in the latitudinal (northsouth) direction. Within the area covered by the grid, there are cells for which no data was collected. These cells are to be left blank on the map.
All cells are of equal size and are oriented so that their corners coincide with the intersections of the gridlines. Figure 1 shows a sample map grid with 8 cells in the longitudinal direction and 3 cells in the latitudinal direction. The map wraps around at the left and right edges. The areas containing data are represented by shaded cells. In the following discussion, the shaded cells are referred to as map cells.
Figure 1. Sample map grid.During the mapproduction process, it will be necessary to identify all points on the grid that are shared by more than one map cell. You are to write a program that reports all such points on the grid and the number of map cells sharing each point.
Input
The first line of input will contain the dimensions L and M of the map, represented as the numbers of cells in the longitudinal (x) and latitudinal (y) directions, respectively. Both numbers will be integers separated by whitespace. You can assume that L is an integer in the range [3, 720] and M an integer whose value is constrained by L and the requirements on the map.
The second line of input will contain the total number of map cells, P. You can assume that P is a positive integer that does not exceed the maximum allowed by the map dimensions.
The final P lines of input will be a list of the map cells. Each cell will be identified by the (integer) grid coordinates of its southwest (lower left) corner on the map, where (0, 0) is defined to be the coordinates of the southwest corner of the grid. Each cell is one unit wide in the xdimension and one unit high in the ydimension. One cell will be identified per line of input. On each line, the xcoordinate will be specified first, followed by whitespace, followed by the ycoordinate. The cells will be ordered randomly. You can assume that the map cells will be within the bounds of the defined map, and that the xcoordinates are constrained to the range [0, L  1].
Output
Your program should list all the unique grid points that are shared by at least two map cells. For each shared grid point, output on a single line the point's xcoordinate, ycoordinate, and the number of map cells sharing that point, all separated by one blank and with no leading or trailing whitespace on the line. Output the grid points (if any) along the southern border of the map first, in order from west to east, starting at xcoordinate 0; continue in the same manner along successive lines of latitude, ending with the northern border of the map. If no shared grid points can be found in the entire map, your program should print the string
NO SHARED CORNERS
and exit. Note that since the map wraps around the world at its eastern border, points along the map's eastern border are the same as those along its western border and should not be reported twice.Sample Input
8 3 10 0 0 0 1 1 1 1 2 3 1 4 2 5 2 5 1 5 0 7 1Sample Output
0 1 3 1 1 3 5 1 2 6 1 2 0 2 2 1 2 3 2 2 2 4 2 2 5 2 3 6 2 2 5 3 2______________________________________________________ 2141false
Your competitors in the low end routing business are adding firewall type features and your sales department is frantic. Sales wants to add access lists ASAP. The marketeers also require that `wire speed' routing not be compromised, but the routing engine is underpowered. Your job is to write a simulator to help answer the performance questions.
Engineering has used a sniffer to record network traAEc and to extract the relevant information from the packet headers, generating a stream of simulated traAEc. Here are some samples of the simulated traffic packets:
216.35.137.204 0 204.69.7.5 0 1 204.69.3.100 49152 204.69.7.109 53 17 24.218.179.217 27015 204.69.0.4 2326 17 148.246.129.175 6699 204.69.2.85 1138 6The packet fields are:
Field Number  Contents  Format 
1  source IP address  dotted decimal address 
2  source port  decimal number 
3  destination IP address  dotted decimal address 
4  destination port  decimal number 
5  protocol  decimal number 
The fields are separated by one or more blanks and the first field may be preceded by one or more blanks. A dotted decimal address is a 32bit value, high order byte first, with the decimal representation of each 8bit byte [0..255] separated by a `.'. For example, 1.2.255.15 is 0x0102FF0F. Ports are in the range [0..65535]. Note that ports are significant for the TCP (6) and UDP (17) protocols only. The port fields will be 0 for other protocols. The protocol is in the range [0..255].
You will be given sample access lists. They will be syntactically correct with fields that are separated by one or more blanks. Some example entries are:
* 1.2.3.4 255.255.0.15 3 5.6.7.8 0.0.255.255 9 Permit 6 0.0.0.0 0.0.0.0 * 204.69.4.254 255.255.255.255 01023 deny
The access list fields are:
Field Number  Contents  Format 
1  protocol  decimal number or `*' 
2  source IP address  dotted decimal address 
3  source mask  dotted decimal mask 
4  source port  decimal number or `*' or a range 
5  destination IP address  dotted decimal address 
6  destination mask  dotted decimal mask 
7  destination port  decimal number or `*' or a range 
8  action  `permit' or `deny' (case is not significant) 
A range is two decimal numbers separated by `' with no whitespace between the numbers and the `'. For example, 552 will match
5port number52. In the access list, the protocol and the ports can be specified as `*', which means match any protocol or port.
A dotted decimal mask is the same format as an address. It indicates which bits are significant when comparing addresses. For example, the addresses 123.234.248.14 and 123.234.254.126 match when compared using the mask 255.255.240.15 (0xFFFFF00F). The 1 bits in the mask show which bits in the addresses to compare. Note that a mask of 0.0.0.0 will cause any address pair to match.
Each simulated traffic packet is compared with the access list entries, in the same order those entries were entered, until the packet matches an entry. For a match to occur, the protocol, source and destination addresses (using the respective masks), and ports must all match. In the real router, the action directs the router to accept or reject the packet, but the simulator just keeps track of how many access list entries are compared, and the number of times each action is taken. For example, if a packet matches the 3rd, 5th, and 8th entries in a 30entry access list, with the action of the 3rd entry being `permit', then processing that packet will contribute 3 comparisons and add 1 to the number of `permit' actions taken. If the action were `deny', 3 would also be added to the comparison count, but 1 would be added to the `deny' count. In either case the 5th and 8th entries are not examined. The first entry that matches is the last examined for a given packet.
Input is a series of test cases. Each test case consists of the access list entries terminated by a blank line. The simulated packet traffic data follows. Each line will be at most 100 characters. The test case is terminated by a blank line or endoffile. Each test case will have at most 100 access list entries.
For each test case print three numbers: the total count of access list entries compared, the number of simulated packets resulting in the `permit' action, and the number of simulated packets resulting in the `deny' action. Put no leading spaces before the first number and exactly one space before the second and third numbers.
* 204.69.0.0 255.255.248.0 * 0.0.0.0 0.0.0.0 * permit * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * DENY 204.69.6.230 3072 24.115.85.245 23 6 192.168.215.17 53 204.248.52.7 1243 17 204.69.12.21 2118 152.163.241.11 21 6 * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * deny 192.102.199.19 27961 63.20.61.96 65535 17 6 198.138.176.100 255.255.255.255 * 204.69.4.100 255.255.255.255 111 permit 6 0.0.0.0 0.0.0.0 * 204.69.0.0 255.255.240.0 111 deny 6 0.0.0.0 0.0.0.0 * 204.69.0.0 255.255.248.0 80 permit * 0.0.0.0 0.0.0.0 * 204.69.0.255 255.255.248.255 * deny * 204.69.0.0 255.255.248.0 * 0.0.0.0 0.0.0.0 * deny * 127.0.0.0 255.0.0.0 * 0.0.0.0 0.0.0.0 * deny * 0.0.0.0 0.0.0.0 * 204.69.7.240 255.255.255.240 99909999 deny * 0.0.0.0 0.0.0.0 * 0.0.0.0 0.0.0.0 * permit 204.69.4.87 80 204.69.9.12 6776 6 134.79.112.65 2186 204.69.4.218 21 6 216.112.217.140 2212 204.69.5.255 22 6 198.138.176.100 1053 204.69.4.100 111 6 198.138.176.100 1054 204.69.5.100 111 6
5 1 2 1 0 1 20 2 3
______________________________________________________ 2142false
The human rights organization, PeopleFirst, has observers around the world checking up on human rights abuses in various countries. Since some countries take a dim view of this sort of activity, PeopleFirst needs a way for their observers to report abuses without the countries they are residing in realizing that a report is being made. The idea is this: Their observers will create websites where they will display photographs of their sightseeing trips, collections, or other hobbies, but the pictures will be subtly altered to hide the reports in them.
There is software available to do this, but PeopleFirst doesn't want to run the risk that some government will try one of these programs on their observer's pictures and find a hidden message. To avoid that, one of their members has written a custom program for hiding messages in pictures. Unfortunately, she had to leave on her own stint as an observer before she could write the program that extracts the messages from the pictures. That's where you come in. You've been asked to write the missing program.
The observer's photographs are posted to their web sites in GIF format. Prior to being given to your program, the pictures are run through a filter that converts them to ppm format, so your program has a simpler picture representation to work with. The ppm format begins with the two characters ``P6" followed by whitespace, most often a single linefeed character. This is followed by the picture width and height formatted as two decimal numbers in ASCII, separated by whitespace. The height is followed by more whitespace, again most often a single linefeed. Following this is the maximum color component value: a decimal number in ASCII. This is the value of the brightest shade for any of the three primary colors in a pixel. You should ignore this value and treat it as if it were 255. This is immediately followed by a single whitespace character, usually a linefeed. Immediately after the whitespace character are 3 x width x height bytes representing a left to right, top to bottom scan of the pixels in the picture, three bytes per pixel, representing the shades of red, green and blue for the pixel, in that order. Treat each byte as an unsigned binary number representing the shade.
The message is hidden in the picture by altering the original pixel values slightly. Each pixel in the picture encodes one bit of the message, which is extracted by taking the exclusiveor of the low order bits of the shades of red, green and blue that make up the pixel. Message bits are assigned to pixels from left to right in rows, starting with the top left pixel in the picture, and ending with the bottom right pixel. The first thing encoded in the picture is the length of the message. It is encoded as 32 bits of binary, starting with the low order bit. The length is immediately followed by the bytes of the message, each byte encoded with the low order bit first. The message is immediately followed by a 32bit checksum, with the low order bit appearing first.
The checksum is calculated from all of the bytes of the message length and the message. In calculating the checksum, the bytes of the message length are ordered with the low order byte first. Initialize the checksum to hexadecimal ffffffff. For each byte that goes into the checksum, first do a single bit left circular shift of the 32 bits of the checksum, then add the byte as an unsigned value, ignoring any overflow.
Output consists of the extracted message, or an error message if no hidden message was found in the input picture. A bad message length or invalid checksum indicate that the input picture has no hidden message.
If the extracted message length is zero, output the following error message and exit before producing any other output:
No message found: message length is zero
If the extracted message length has a value so large that there wouldn't be enough pixels in the input picture to encode all of the bits of the message length, message and checksum, output the following error message and exit before producing any other output:
No message found: bad length: msz bits > psz pixels
In the actual message, replace msz with the number of bits needed to encode the message length, message and checksum; replace psz with the number of pixels in the picture. Output both numbers in decimal.
If the checksum you calculate does not equal the extracted checksum, output the following error message and exit before producing any other output:
No message found: bad checksum: recorded = rcs, calculated = ccs
In the actual message, replace rcs with the extracted checksum, and replace ccs with the calculated checksum. Output both checksums with the prefix `0x', followed by 8 hexadecimal digits, using lower case for the alphabetic hexadecimal digits. The string `0x13579bdf' would be one example of the required format.
The judge's data will have no improperly formatted input or require impossibly large memory allocations. Consequently, the three defined errors will be the only ones that can appear legally in your output.
Note that the ppm formatted picture is likely to contain many unprintable characters, and there is no requirement that the message consists solely of printable characters either. The sample input printed on this page has `
' to indicate spaces and the expression `<ffl>
'
that represent 0x0a (linefeed). Each line is broken after the occurrence of 0x0a for readability. To view your input and output, the od command should prove useful. To view the pictures as pictures, you can use xloadimage. A more interesting example is available via the getdata command: the picture, jellies.ppm, hides another picture, the GIF file, redrose.gif.
P6<ffl> 8 12<ffl> 255<ffl> !}~ ~p }` ~P ~@~ 0 ~ ~<ffl> 0~~0~p0~`0~P0~@0~0/~!0~<ffl> )}~@~p@~`@~P@~@@~0@~ @~<ffl> P~~P~pP~`P~PP~@P~0P~ P~<ffl> `~~`~p`~``~Q`~@`~0`~!`~<ffl> o}}o~qp~`p~Op~@p~/p~!p~<ffl> ~q~~pp~p`~pP~p@~p1~p ~p<ffl> ~`~~ap~``~_P~`@~`0~` ~`<ffl> ~P~~Pp~P`~PP~P)}Q1~O_~Q<ffl> ~A~~@p~@a~@P~@@~@0~@ ~@<ffl> ~0~~0p~0`~0P~0@~00~0 ~0<ffl> ~ ~~ p~ `~ P~ @~ 0~ ~"<ffl>
Hi!
Note the space characters `
' and 0x0a `<ffl>
'
______________________________________________________ 2143false
Swamp County has gotten new hardware for handling and reading ballots, so they need to replace their vote counting software. Frugal as always, the county supervisors have found volunteer labor, you, to develop the software, so they can use the savings as justification for voting themselves hefty raises as a reward for saving the county so much money.
Here's what you have to do to fulfill your civic duty: Write a program that accepts a description of the choices before the voters in the election and how those choices are represented on the ballot, reads the raw ballots, and prints the results.
To avoid wordiness, we will use the word ``question" to represent the office, proposition, or other question put before the voters, and the word ``choice" to represent the candidates, ``yes" or ``no," or the other choices voters can make on a question. The ballots used in Swamp County have prerecorded precinct numbers, and contain 384 positions (numbered from 1 to 384) that can be used to record voters' choices. Only a small number of these positions will be used in any election to represent choices on ballot questions.
Input is in three sections, each of which consists of several lines. Every line will contain one or more data items, and is terminated by a newline character. The format of the data items is described later.
The first section is a description of the ballot questions. This section begins with a line containing a single number which gives the total number of ballot questions. It is followed by the descriptions of the questions themselves, each in its own subsection. Questions are numbered, starting with 1, in the order that they appear in this section.
The first line of the subsection for a ballot question contains its name. The second line contains two numbers, the first of which is the number of choices for this question. The second number is the number of choices that can be voted for on the question, since some questions, like positions on a party's central committee, allow you to vote for more than one candidate. The remaining lines are the names of the choices, one per line. The choices are numbered from 1, in the order they appear in the question.
The second section is a description of the ballots, which has a separate subsection for each precinct, since which questions are voted on and the order of the choices may vary by precinct. The first line in this section contains the number of precincts in the county. It is followed by the subsections describing the ballots in each precinct.
The first line of a precinct ballot description subsection contains two numbers: the precinct number, and the number of ballot positions in use on ballots in that precinct. The following lines associate one of those ballot positions with the vote it represents. Each line contains a ballot position number and the question and choice numbers associated with that ballot position. Thus a line containing `31 2 5' indicates that a vote in position 31 on that precinct's ballot is a vote for choice 5 of question 2, as given in the description of the ballot questions in the first section of input.
The last section is the raw ballot information, one line per ballot, until endoffile. A ballot line starts with the precinct number for the ballot, right justified in a 4character field. This field is followed (after a single blank) by 48 pairs of hexadecimal digits encoding the 384bit bit string that represents how the ballot was voted. In this representation, the bits in the bit string are numbered from 1 to 384, and each position on the ballot is represented by the identically numbered bit. That bit is 1 if the corresponding ballot position is marked, and 0 if it is not marked. In the string of 96 hexadecimal digits that encodes this bit string, bit number 1 is the high order bit of the first hex digit, and the numbering proceeds from high order to low order bit in each hexadecimal digit, until bit number 384, which is the low order bit of the last hex digit. Count the ballots, starting at 1 as you read them, in case you need to report an error on that ballot.
Numbers are represented by strings of decimal digits in ASCII. Bit strings are represented by strings of pairs of hexadecimal digits, as already described. Multiple numbers and bit strings can appear on the same line, separated by single blanks. Character strings are represented by a single line of printable characters, including blanks, but excluding the newline character that terminates the line.
Ballots must be checked for validity before they can be counted. If the precinct number on a ballot is not known (did not appear in the ballot description section of the input), print the ballot number and the string ``bad precinct" as an error message. If a ballot has any marks in positions that do not correspond to any ballot choices for ballots in that precinct, print the ballot number and the string ``stray mark" as an error message. Either of these two errors will void the entire ballot. Do not count any votes from such a ballot.
If a ballot has votes for more than the allowed number of choices on a question, only the vote on that question is voided. This error does not void the entire ballot. If this happens, print the ballot number, the question number, and the string, ``too many votes" as an error message. Do not count the vote for any choice on that question (or any other voided question) on the ballot, but do count the votes for any questions that have not been voided on that ballot.
Each error message should be on a single line and should contain just the numbers and strings mentioned. There should be just a single blank character between each number and string. Do your validity checks for each ballot in the order given. If the precinct is bad, don't bother checking anything else. If there are stray marks, don't bother reporting that some questions may have too many votes. For any ballot, report too many votes on more than one question in the order of their question numbers. If there are any error messages, follow them by three empty lines to separate them from the result output.
The first line of result output should start with 32 blanks, followed by the string ``Election Results", providing a title for the election results. The title line is followed by an empty line and then the results for each question in the order they were presented in the first section of the input.
The result for each question is output as a line containing 8 blanks and the name of the question, followed by an empty line, followed by one line for each choice in that question, in the order they appeared in the first section of the input. The line for each choice begins with the choice name, left justified in a field of 64 characters, followed by a single space followed by the number of votes for that choice, right justified in a field of 10 characters, followed by a single space, followed by the percentage of the vote for that choice on that question, rounded to the nearest integer, right justified in a field of 3 characters, and followed by a percent sign. Note that the percentage is the percentage of ballots cast on that question that voted for that choice. That means that, if you can vote for 2 choices on that question, the percentages, subject to rounding error, can add up to 200%. Always round .5 up.
The output of the results for the ballot questions should be separated from each other by single empty lines, and there should be no empty line after the results for the last question.
No input line in the ballot description sections is longer than 64 characters, while every raw ballot is represented by a line that is exactly 101 characters long. The line lengths do not include the line terminator.
3 President 5 1 Bugs Bunny Daffy Duck Goofy Kenshiro Mickey Mouse Justice League of America 6 4 Aquaman Batman Superman Spiderman The Flash The Green Lantern Justice League of America Membership: Should Spidey be Eligible? 2 1 Yes No 3 122 5 2 1 3 4 1 2 6 1 5 8 1 1 10 1 4 43 13 2 1 5 4 1 2 6 1 1 8 1 4 10 1 3 21 2 6 23 2 3 25 2 2 27 2 4 29 2 1 31 2 5 70 3 1 75 3 2 8365 5 3 1 1 6 1 4 9 1 5 12 1 2 15 1 3 43 10000A880000000004000000000000000000000000000000 000000000000000000000000000000000000000000000000 43 004002A20000000000200000000000000000000000000000 000000000000000000000000000000000000000000000000 43 040008AA0000000004000000000000000000000000000000 000000000000000000000000000000000000000000000000 122 004000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 233 004400000000010000000080000000000000000000000000 000000008000000000000000000000000000000000000000 122 040000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000001 43 100008A00000000000200000000000000000000000000000 000000000000000000000000000000000000000000000000 8365 008000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 43 100002A20000000004000000000000000000000000000000 000000000000000000000000000000000000000000000000 8365 200000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 43 40000A200000000004000000000000000000000000000000 000000000000000000000000000000000000000000000000 43 000002A00000000004000000000000000000000000000000 000000000000000000000000000000000000000000000000 43 10000AA00000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000
3 2 too many votes 5 bad precinct 6 stray mark Election Results President Bugs Bunny 2 20% Daffy Duck 4 40% Goofy 1 10% Kenshiro 1 10% Mickey Mouse 2 20% Justice League of America Aquaman 1 14% Batman 6 86% Superman 6 86% Spiderman 6 86% The Flash 2 29% The Green Lantern 4 57% Justice League of America Membership: Should Spidey be Eligible? Yes 5 71% No 2 29%
______________________________________________________ 2144false
Every year Swamp County holds its regional collegiate programming contest. One part of running the programming contest is assigning teams to workstations. The organizers attempt to locate teams such that teams from the same school are not assigned workstations close to each other. In the past this has been an ad hoc process. Your team will develop an application to allow the organizers to compare their ad hoc workstation assignments with the best possible layout.
Input to your program is a list of Cartesian coordinates of workstation locations (in integer feet) followed by one line per school giving the number of teams from the school and the school name. There will be a maximum of 14 workstations, and 4 teams per school. The last workstation will always be located at `0,0'. The dimensions of the largest possible workstation lab are 200 by 200 feet. Also, the number of teams will not exceed the number of workstations, and there will always be at least one school with at least two teams.
Output from your program is the square of the minimum distance between any two teams from the same school after teams have been assigned workstations that maximize this distance. The output is one line containing the left justified integer value that is the squared distance.
3,0 6,0 9,0 0,2 3,2 6,2 9,2 0,5 3,5 6,5 9,5 14,3 14,6 0,0 3 Bogy U 3 Gator State 1 Armadillo Tech 2 CFTBL City College 1 Moss Institute 3 SC Polytechnic
34 ______________________________________________________ 2145falseWilliam Robinson was completely puzzled in the music room; he could not find his triangle in his bag. He was sure that he had prepared it the night before. He remembered its clank when he had stepped on the school bus early that morning. No, not in his dream. His triangle was quite unique:no two sides had the same length, which made his favorite peculiar jingle. He insisted to the music teacher, Mr. Smith, that his triangle had probably been stolen by those aliens and thrown away into deep space.
Your mission is to help Will find his triangle in space. His triangle has been made invisible by the aliens, but candidate positions of its vertices are somehow known. You have to tell which three of them make his triangle. Having gone through wormholes, the triangle may have changed its size. However, even in that case, all the sides are known to be enlarged or shrunk equally, that is, the transformed triangle is similar to the original.
Input
The very first line of the input has an integer which is the number of data sets. Each data set gives data for one incident such as that of Will's.
The first line of each data set contains three decimals that give lengths of the sides of the original triangle, measured in centimeters. Three vertices of the original triangle are named P, Q, and R. Three decimals given in the first line correspond to the lengths of sides QR, RP, and PQ, in this order. They are separated by one or more space characters.
The second line of a data set has an integer which is the number of points in space to be considered as candidates for vertices. At least three and at most thirty points are considered.
The rest of the data set are lines containing coordinates of candidate points, in light years. Each line has three decimals, corresponding to x, y, and z coordinates, separated by one or more space characters. Points are numbered in the order of their appearances, starting from one.
Among all the triangles formed by three of the given points, only one of them is similar to the original, that is, ratios of the lengths of any two sides are equal to the corresponding ratios of the original allowing an error of less than 0.01 percent. Other triangles have some of the ratios different from the original by at least 0.1 percent.
The origin of the coordinate system is not the center of the earth but the center of our galaxy. Note that negative coordinate values may appear here. As they are all within or close to our galaxy, coordinate values are less than one hundred thousand light years. You don't have to take relativistic effects into account, i.e., you may assume that we are in a Euclidean space. You may also assume in your calculation that one light year is equal to 9.461 x 10^{12} kilometers.
A succeeding data set, if any, starts from the line immediately following the last line of the preceding data set.
Output
For each data set, one line should be output. That line should contain the point numbers of the three vertices of the similar triangle, separated by a space character. They should be reported in the order P, Q, and then R.
Sample Input
2 50.36493 81.61338 79.96592 5 10293.83 4800.033 5296.238 14936.30 6964.826 7684.818 4516.069 25748.41 27016.06 18301.59 11946.25 5380.309 27115.20 43415.93 71607.81 11.51547 13.35555 14.57307 5 56292.27 2583.892 67754.62 567.5082 756.2763 118.7268 1235.987 213.3318 216.4862 317.6108 54.81976 55.63033 22505.44 40752.88 27482.94Sample Output
1 2 4 3 4 2______________________________________________________ 2146false
A professor of anthropology was interested in people living in isolated islands and their history. He collected their family trees to conduct some anthropological experiment. For the experiment, he needed to process the family trees with a computer. For that purpose he translated them into text files. The following is an example of a text file representing a family tree.
John Robert Frank Andrew Nancy DavidEach line contains the given name of a person. The name in the first line is the oldest ancestor in this family tree. The family tree contains only the descendants of the oldest ancestor. Their husbands and wives are not shown in the family tree. The children of a person are indented with one more space than the parent. For example, Robert and Nancy are the children of John, and Frank and Andrew are the children of Robert. David is indented with one more space than Robert, but he is not a child of Robert, but of Nancy. To represent a family tree in this way, the professor excluded some people from the family trees so that no one had both parents in a family tree.
For the experiment, the professor also collected documents of the families and extracted the set of statements about relations of two persons in each family tree. The following are some examples of statements about the family above.
John is the parent of Robert. Robert is a sibling of Nancy. David is a descendant of Robert.For the experiment, he needs to check whether each statement is true or not. For example, the first two statements above are true and the last statement is false. Since this task is tedious, he would like to check it by a computer program.
Input
The input contains several data sets. Each data set consists of a family tree and a set of statements. The first line of each data set contains two integers n (0 < n < 1000) and m (0 < m < 1000) which represent the number of names in the family tree and the number of statements, respectively. Each line of the input has less than 70 characters.
As a name, we consider any character string consisting of only alphabetic characters. The names in a family tree have less than 20 characters. The name in the first line of the family tree has no leading spaces. The other names in the family tree are indented with at least one space, i.e., they are descendants of the person in the first line. You can assume that if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces. This guarantees that each person except the oldest ancestor has his or her parent in the family tree. No name appears twice in the same family tree. Each line of the family tree contains no redundant spaces at the end.
Each statement occupies one line and is written in one of the following formats, where X and Y are different names in the family tree.
X is a child of Y.
X is the parent of Y.
X is a sibling of Y.
X is a descendant of Y.
X is an ancestor of Y.
Names not appearing in the family tree are never used in the statements. Consecutive words in a statement are separated by a single space. Each statement contains no redundant spaces at the beginning and at the end of the line.The end of the input is indicated by two zeros.
Output
For each statement in a data set, your program should output one line containing True or False.
The first letter of `True' or `False' in the output must be a capital. The output for each data set should be followed by an empty line.
Sample Input
6 5 John Robert Frank Andrew Nancy David Robert is a child of John. Robert is an ancestor of Andrew. Robert is a sibling of Nancy. Nancy is the parent of Frank. John is a descendant of Andrew. 2 1 abc xyz xyz is a child of abc. 0 0Sample Output
True True True False False True______________________________________________________ 2147false
Mr. Schwarz was a famous powerful pro wrestler. He starts a part time job as a warehouseman. His task is to move a cargo to a goal by repeatedly pushing the cargo in the warehouse, of course, without breaking the walls and the pillars of the warehouse.
There may be some pillars in the warehouse. Except for the locations of the pillars, the floor of the warehouse is paved with square tiles whose size fits with the cargo. Each pillar occupies the same area as a tile.
Initially, the cargo is on the center of a tile. With one push, he can move the cargo onto the center of an adjacent tile if he is in proper position. The tile onto which he will move the cargo must be one of (at most) four tiles (i.e., east, west, north or south) adjacent to the tile where the cargo is present.
To push, he must also be on the tile adjacent to the present tile. He can only push the cargo in the same direction as he faces to it and he cannot pull it. So, when the cargo is on the tile next to a wall (or a pillar), he can only move it along the wall (or the pillar). Furthermore, once he places it on a corner tile, he cannot move it anymore.
He can change his position, if there is a path to the position without obstacles (such as the cargo and pillars) in the way. The goal is not an obstacle. In addition, he can move only in the four directions (i.e., east, west, north or south) and change his direction only at the center of a tile.
As he is not so young, he wants to save his energy by keeping the number of required pushes as small as possible. But he does not mind the count of his pedometer, because walking is very light exercise for him.
Your job is to write a program that outputs the minimum number of pushes required to move the cargo to the goal, if ever possible.
Input
The input consists of multiple maps, each representing the size and the arrangement of the warehouse. A map is given in the following format.
w  h  
d_{11}  d_{12}  d_{13}  ^{... }  d_{1w} 
d_{21}  d_{22}  d_{23}  ^{... }  d_{2w} 
^{... }  
d_{h1}  d_{h2}  d_{h3}  ^{... }  d_{hw} 
The integers w and h are the lengths of the two sides of the floor of the warehouse in terms of widths of floor tiles. w and h are less than or equal to 7. The integer d_{ij} represents what is initially on the corresponding floor area in the following way.
Each of the integers 2, 3 and 4 appears exactly once as d_{ij} in the map. Integer numbers in an input line are separated by at least one space character. The end of the input is indicated by a line containing two zeros.
For each map, your program should output a line containing the minimum number of pushes. If the cargo cannot be moved to the goal, `1' should be output instead.
5 5 0 0 0 0 0 4 2 0 1 1 0 1 0 0 0 1 0 0 0 3 1 0 0 0 0 5 3 4 0 0 0 0 2 0 0 0 0 0 0 0 0 3 7 5 1 1 4 1 0 0 0 1 1 2 1 0 0 0 3 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 6 6 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 4 0 0 0 0 0 0 0
5 1 11 8
______________________________________________________ 2148false
Bill is a boss of security guards. He has pride in that his men put on wearable computers on their duty. At the same time, it is his headache that capacities of commercially available batteries are far too small to support those computers all day long. His men come back to the office to charge up their batteries and spend idle time until its completion. Bill has only one battery charger in the office because it is very expensive.
Bill suspects that his men spend much idle time waiting in a queue for the charger. If it is the case, Bill had better introduce another charger. Bill knows that his men are honest in some sense and blindly follow any given instructions or rules. Such a simpleminded way of life may lead to longer waiting time, but they cannot change their behavioral pattern.
Each battery has a data sheet attached on it that indicates the best pattern of charging and consuming cycle. The pattern is given as a sequence of pairs of consuming time and charging time. The data sheet says the pattern should be followed cyclically to keep the battery in quality. A guard, trying to follow the suggested cycle strictly, will come back to the office exactly when the consuming time passes out, stay there until the battery has been charged for the exact time period indicated, and then go back to his beat.
The guards are quite punctual. They spend not a second more in the office than the time necessary for charging up their batteries. They will wait in a queue, however, if the charger is occupied by another guard, exactly on firstcomefirstserved basis. When two or more guards come back to the office at the same instance of time, they line up in the order of their identifi cation numbers, and, each of them, one by one in the order of that line, judges if he can use the charger and, if not, goes into the queue. They do these actions in an instant.
Your mission is to write a program that simulates those situations like Bill's and reports how much time is wasted in waiting for the charger.
The input consists of one or more data sets for simulation.
The first line of a data set consists of two positive integers separated by a space character:the number of guards and the simulation duration. The number of guards does not exceed one hundred. The guards have their identification numbers starting from one up to the number of guards. The simulation duration is measured in minutes, and is at most one week, i.e., 10080 (min.).
Patterns for batteries possessed by the guards follow the first line. For each guard, in the order of identification number, appears the pattern indicated on the data sheet attached to his battery. A pattern is a sequence of positive integers, whose length is a multiple of two and does not exceed fifty. The numbers in the sequence show consuming time and charging time alternately. Those times are also given in minutes and are at most one day, i.e., 1440 (min.). A space character or a newline follows each number. A pattern is terminated with an additional zero followed by a newline.
Each data set is terminated with an additional empty line. The input is terminated with an additional line that contains two zeros separated by a space character.
For each data set your program should simulate up to the given duration. Each guard should repeat consuming of his battery (i.e., being on his beat) and charging of his battery according to the given pattern cyclically. At the beginning, all the guards start their cycle simultaneously, that is, they start their beats and, thus, start their first consuming period.
For each data set, your program should produce one line containing the total wait time of the guards in the queue up to the time when the simulation duration runs out. The output should not contain any other characters.
For example, consider a data set:
3 25 3 1 2 1 4 1 0 1 1 0 2 1 3 2 0
The guard 1 tries to repeat 3 min. consuming, 1 min. charging, 2 min. consuming, 1 min. charging, 4 min. consuming, and 1 min. charging, cyclically. Yet he has to wait sometimes to use the charger, when he is on his duty together with the other guards 2 and 3. Thus, the actual behavior of the guards looks like:
0 10 20       guard 1: ***.**.****.***.**.****. guard 2: *.*.*.*.*.*.*.*.*.* guard 3: **.***..**.***..**.***where ``*" represents a minute spent for consuming, ``." for charging, and ``" for waiting in the queue. At time 3, the guards 1 and 2 came back to the office and the guard 1 started charging while the guard 2 went into the queue. At time 6, all the guards came back to the office and the guard 1 started charging while the others went to the queue. When the charger got available at time 7, the guard 2 started charging, leaving the guard 3 in the queue. All those happened are consequences of rules stated above. And the total time wasted in waiting for the charger becomes 10 minutes.
3 25 3 1 2 1 4 1 0 1 1 0 2 1 3 2 0 4 1000 80 20 80 20 80 20 80 20 0 80 20 0 80 20 90 10 80 20 0 90 10 0 0 0
10 110
______________________________________________________ 2149false
Haven't you ever thought that programs written in Java, C++, Pascal, or any other modern computer languages look rather sparse? Although most editors provide sufficient screen space for at least 80 characters or so in a line, the average number of significant characters occurring in a line is just a fraction. Today, people usually prefer readability of programs to efficient use of screen real estate.
Dr. Faust, a radical computer scientist, believes that editors for real programmers shall be more space efficient. He has been doing research on saving space and invented various techniques for many years, but he has reached the point where no more essential improvements will be expected with his own ideas.
After long thought, he has finally decided to take the ultimate but forbidden approach. He does not hesitate to sacrifice anything for his ambition, and asks a devil to give him supernatural intellectual powers in exchange with his soul. With the transcendental knowledge and ability, the devil provides new algorithms and data structures for space efficient implementations of editors.
The editor implemented with those evil techniques is beyond human imaginations and behaves somehow strange. The mighty devil Dr. Faust asks happens to be the devil of gravity. The editor under its control saves space with magical magnetic and gravitational forces.
Your mission is to defeat Dr. Faust by reimplementing this strange editor without any help of the devil. At first glance, the editor looks like an ordinary text editor. It presents texts in twodimensional layouts and accepts editing commands including those of cursor movements and character insertions and deletions. A text handled by the devil's editor, however, is partitioned into text segments, each of which is a horizontal block of nonblank characters. In the following figure, for instance, four text segments ``abcdef", ``ghijkl", ``mnop", ``qrstuvw" are present and the first two are placed in the same row.
abcdef ghijkl mnop qrstuvw
The editor has the following unique features.
For instance, if characters in the segment ``mnop" in the previous example are deleted, the two segments on top of it fall and we have the following.
abcdef qrstuvw ghijkl
After that, if ``x" is added at the tail (i.e., the right next of the rightmost column) of the segment ``qrstuvw", the two segments in the bottom row are concatenated.
abcdef qrstuvwxghijkl
Now we have two text segments in this figure. By this way, the editor saves screen space but demands the users' extraordinary intellectual power.
In general, after a command execution, the following rules are applied, where S is a text segment, left(S) and right(S) are the leftmost and rightmost columns of S, respectively, and row(S) is the row number of S.
Note that any text segment has at least one character. Note also that the first rule is applied prior to any application of the second rule. This means that no concatenation may occur while falling segments exist. For instance, consider the following case.
dddddddd cccccccc bbbb aaa
If the last character of the text segment ``bbbb" is deleted, the concatenation rule is not applied until the two segments ``cccccccc" and ``dddddddd" stop falling. This means that ``bbb" and ``cccccccc" are not concatenated.
The devil's editor has a cursor and it is always in a single text segment, which we call the current segment. The cursor is at some character position of the current segment or otherwise at its tail. Note that the cursor cannot be a support. For instance, in the previous example, even if the cursor is at the last character of ``bbbb" and it stays at the same position after the deletion, it cannot support ``cccccccc" and ``dddddddd" any more by solely itself and thus those two segments shall fall. Finally, the cursor is at the leftmost ``d"
The editor accepts the following commands, each represented by a single character.
Note that after executing this command, some text segments may lose their supports and be pulled down toward the hell. If the current segment falls, the cursor also falls with it.
Once an error occurs, the entire editing session terminates abnormally.
The first line of the input contains an integer that represents the number of editing sessions. Each of the following lines contains a character sequence, where the first character is the initial character and the rest represents a command sequence processed during a session. Each session starts with a single segment consisting of the initial character in the bottom row. The initial cursor position is at the tail of the segment. The editor processes each command represented by a character one by one in the manner described above.
You may assume that each command line is nonempty and its length is at most one hundred. A command sequence ends with a newline.
For each editing session specified by the input, if it terminates without errors, your program should print the current segment at the completion of the session in a line. If an error occurs during the session, just print ``ERROR" in capital letters in a line.
3 12BC3BC4BNBBDD5 aaaBCNBBBCb aaaBBCbNBC
15234 aba ERROR
______________________________________________________ 2150false
A scientist discovered a strange variation of amoeba. The scientist named it numoeba. A numoeba, though it looks like an amoeba, is actually a community of cells, which always forms a tree.
The scientist called the cell leader that is at the root position of the tree. For example, in Fig. 1, the leader is A. In a numoeba, its leader may change time to time. For example, if E gets new leadership, the tree in Fig. 1 becomes one in Fig. 2. We will use the terms root, leaf, parent, child and subtree for a numoeba as defined in the graph theory.
B  C  D  
E  F  
G 
A  B  C  D  
F  
G 
Numoeba changes its physical structure at every biological clock by cell division and cell death. The leader may change depending on this physical change.
The most astonishing fact about the numoeba cell is that it contains an organic unit called numbosome, which represents an odd integer within the range from 1 to 12,345,677. At every biological clock, the value of a numbosome changes from n to a new value as follows:
For example, if the numbosome value of a cell is 13, 13 x 3 + 1 = 40 is divided by 2^{3} = 8 and a new numbosome value 5 is obtained. If the numbosome value of a cell is 11,111,111, it changes to 4,320,989, instead of 16,666,667. If 3n + 1 is a power of 2, yielding 1 as the result, it signifies the death of the cell as will be described below.
At every biological clock, the next numbosome value of every cell is calculated and the fate of the cell and thereby the fate of numoeba is determined according to the following steps.
A cell dies if its numbosome value becomes 1. If the dying cell is the leader of the numoeba, the numoeba dies as a whole. Otherwise, all the cells in the subtree from the dying cell (including itself) die. However, there is an exceptional case where the cells in the subtree do not necessarily die; if there is only one child cell of the dying nonleader cell, the child cell will replace the dying cell. Thus, a straight chain simply shrinks if its nonleader constituent dies.
For example, consider a numoeba with the leader A below.
B  C  D  E  F  
G  H 
If the leader A dies in (1), the numoeba dies.
If the cell D dies in (1), (1) will be as follows.
B  C  E  F  
G  H 
And, if the cell E dies in (1), (1) will be as follows.
B  C  D 
Note that this procedure is executed sequentially, topdown from the root of the numoeba to leaves. If the cells E and F will die in (1), the death of F is not detected at the time the procedure examines the cell E. The numoeba, therefore, becomes (3). One should not consider in such a way that the death of F makes G the only child of E, and, therefore, G will replace the dying E.
The following illustrates the growth and death of a numoeba starting from a single cell seed with the numbosome value 15, which plays both roles of the leader and a leaf at the start. In the figure, a cell is nicknamed with its numbosome value. Note that the order of the children of a parent is irrelevant.
clock  structure  comments  
0  15 plays both roles of the leader and a leaf.  
1  13  23 (from 15) is the new leader (again).  
13 is the leaf bonus,  
11  and 11 is the leader bonus.  
2  17  17 is the leader bonus.  
5  35 (from 23) is the new leader (again).  
5 is from 13.  
17  
17 (from 11) spawns  
9  the leaf bonus 9.  
3  13  13 is from 17.  
27  53 (from 35) is the new leader (again).  
27 is the leader bonus.  
13  Note that 5 dies out.  
7  
4  5  5 is from 13.  
5  21  41 (from 27) is the new leader,  
and spawns the leader and leaf bonuses both 21.  
5  21  5 (from 53) loses its leadership.  
11  7  
5  15  only 31 (from 41) survives,  
which spawns the leader bonus 15. 
The numoeba continues changing its structure, and at clock 104, it looks as follows.
11  7  167  11  13  53  
17  5  167  11  13  53  
13  5  167  11  13  53  
5  5  2429  5  161  11  23  13  
2429  5  161  11  23  13 
Here, two ambitious 2429's could not become the leader. The leader 5 will die without promoting these talented cells at the next clock. This alludes the fragility of a big organization.
And, the numoeba dies at clock 105.
Your job is to write a program that outputs statistics about the life of numoebae that start from a single cell seed at clock zero.
A sequence of odd integers, each in a line. Each odd integer k_{i} (3k_{i}9, 999) indicates the initial numbosome value of the starting cell. This sequence is terminated by a zero.
A sequence of pairs of integers:an integer that represents the numoeba's life time and an integer that represents the maximum number of constituent cells in its life. These two integers should be separated by a space character, and each pair should be followed immediately by a newline. Here, the lifetime means the clock when the numoeba dies.
You can use the fact that the life time is less than 500, and that the number of cells does not exceed 500 in any time, for any seed value given in the input. You might guess that the program would consume a lot of memory. It is true in general. But, don't mind. Referees will use a test data set consisting of no more than 10 starting values, and, starting from any of the those values, the total numbers of cells spawned during the lifetime will not exceed 5000.
3 5 7 15 655 2711 6395 7195 8465 0
2 3 1 1 9 11 105 65 398 332 415 332 430 332 428 332 190 421
______________________________________________________ 2151false
Dr. Extreme experimentally made an extremely precise telescope to investigate extremely curi ous phenomena at an extremely distant place. In order to make the telescope so precise as to investigate phenomena at such an extremely distant place, even quite a small distortion is not allowed. However, he forgot the influence of the internal gas affected by lowfrequency vibration of magnetic flux passing through the telescope. The cylinder of the telescope is not affected by the lowfrequency vibration, but the internal gas is.
The cross section of the telescope forms a perfect circle. If he forms a coil by putting extremely thin wire along the (inner) circumference, he can measure (the average vertical component of) the temporal variation of magnetic flux:such measurement would be useful to estimate the influence. But points on the circumference at which the wire can be fixed are limited; furthermore, the number of special clips to fix the wire is also limited. To obtain the highest sensitivity, he wishes to form a coil of a polygon shape with the largest area by stringing the wire among carefully selected points on the circumference.
Your job is to write a program which reports the maximum area of all possible mpolygons (polygons with exactly m vertices) each of whose vertices is one of the n points given on a circumference with a radius of 1. An example of the case n = 4 and m = 3 is illustrated below.
In the figure above, the equations such as `` p_{1} = 0.0" indicate the locations of the n given points, and the decimals such as ``1.000000" on mpolygons indicate the areas of mpolygons.
Parameter p_{i} denotes the location of the ith given point on the circumference (1in). The location p of a point on the circumference is in the range 0p < 1, corresponding to the range of rotation angles from 0 to 2 radians. That is, the rotation angle of a point at p to the point at 0 equals 2p radians. ( is the circular constant 3.14159265358979323846....)
You may rely on the fact that the area of an isosceles triangle ABC (AB = AC = 1) with an interior angle BAC of radians (0 < < ) is sin , and the area of a polygon inside a circle with a radius of 1 is less than .
The input consists of multiple subproblems followed by a line containing two zeros that indicates the end of the input. Each subproblem is given in the following format.
n  m  
p_{1}  p_{2}  ^{... }  p_{n} 
n is the number of points on the circumference (3n40). m is the number of vertices to form mpolygons (3mn). The locations of n points, p_{1}, p_{2},..., p_{n}, are given as decimals and they are separated by either a space character or a newline. In addition, you may assume that 0p_{1} < p_{2} < ^{... }< p_{n} < 1.
For each subproblem, the maximum area should be output, each in a separate line. Each value in the output may not have an error greater than 0.000001 and its fractional part should be represented by 6 decimal digits after the decimal point.
4 3 0.0 0.25 0.5 0.666666666666666666667 4 4 0.0 0.25 0.5 0.75 30 15 0.00 0.03 0.06 0.09 0.12 0.15 0.18 0.21 0.24 0.27 0.30 0.33 0.36 0.39 0.42 0.45 0.48 0.51 0.54 0.57 0.61 0.64 0.66 0.69 0.72 0.75 0.78 0.81 0.84 0.87 40 20 0.351 0.353 0.355 0.357 0.359 0.361 0.363 0.365 0.367 0.369 0.371 0.373 0.375 0.377 0.379 0.381 0.383 0.385 0.387 0.389 0.611 0.613 0.615 0.617 0.619 0.621 0.623 0.625 0.627 0.629 0.631 0.633 0.635 0.637 0.639 0.641 0.643 0.645 0.647 0.649 0 0
1.183013 2.000000 3.026998 0.253581
______________________________________________________ 2152false
Euclid, dwelt in Alexandria, still being convinced firmly that there is no Royal Road to Euclidean Geometry yet, began to feel gradually, reading newspaper articles, watching TV programs, or brainwashed by young students, that it might be possible to create such a discipline as eGeometry or Geometry on the Internet. In an eGeometry environment, he could timely discuss geometry issues with many friends of his including Pythagoras, or he could upload new versions of his unparalleled famous archive ``Elements of Geometry (Stoicheia)" on his WWW site. He instantly made up his mind to join the Internet.
He started laying ether cable himself from the hub to his terminal in his uniquely shaped study. He designed the cable route as short as possible.
Figure 1 is a plan of his study. Integers in a pair of parentheses like (0 0) are x and ycoordinates of the nearest pillar or hub or terminal. Between two adjacent pillars are walls indicated by the solid lines. Suppose A is the position of the hub and B his terminal, then the shortest cable may run as drawn with a broken line.
Your mission is to answer the sequence of the coordinates of turning points of the shortest cable route including those of both ends A and B for each plan. So, you are to answer as:
(1 1) (2 2) (8 4) (9 5)
for the example of Figure 1.
Remember, however, that this is a house of Euclid, the founder and master of Euclidean Geom etry. The pillars, hub and terminal are ideal points of Euclidean Geometry. The walls and cable are line segments in the sense of geometry. Accordingly, the cable may overlap the walls or the pillars. Hence for Figures 2, 3 and 4, the answers should be as follows:(Hereafter, the layouts of the study are given by means of the lists of the pillar coordinates.)
Figure 2: Pillars:
(0 0) (2 0) (2 2) (4 2) (4 0) (6 0) (6 6) (4 6) (4 4) (2 4) (2 6) (0 6)
Hub: (1 1), Terminal: (5 1)
The answer: (1 1) (2 2) (4 2) (5 1)
Figure 3: Pillars:
(0 0) (2 0) (2 2) (4 2) (4 0) (6 0) (6 6) (4 6) (4 4) (2 4) (2 6) (0 6)
Hub: (1 1), Terminal: (5 5)
The answer: (1 1) (5 5)
Warning: (2 2) (4 4) are not the turning points.
Figure 4: Pillars:
(0 0) (2 0) (2 2) (4 2) (4 0) (6 0) (6 2) (8 2) (8 0) (10 0) (10 6) (8 6)
(8 4) (6 4) (6 6) (4 6) (4 4) (2 4) (2 6) (0 6)
Hub: (1 1), Terminal: (9 1)
The answer: (1 1) (2 2) (8 2) (9 1)
All values of coordinates are integers. Walls are parallel to either x or yaxis. Walls turn right or left at each pillar for which the coordinates are given. The coordinates of the pillars are given in the order to look the inside of study to the left. From the last pillar in the list, the next wall stretches to the first pillar. Every position of the pillar appears only once in the list. Each pillar is connected to exactly two walls, one of which is parallel to xaxis and the other to yaxis. The whole wall surrounds the study with single stroke closing line. No walls cross. No wall branches exist. It is known that no independent walls or other obstacles are found inside the study. Only one hub and one terminal exist inside the study for each plan, and their positions are always different.
Submit your program when it could solve for the study of complicated shape like Figure 5. This layout is included in the sample input.
Pillars:
(0 0) (2 0) (2 4) (4 4) (4 0) (14 0) (14 6) (10 6) (10 8) (14 8) (14 14)
(4 14) (4 10) (2 10) (2 14) (0 14) (0 8) (6 8) (6 12) (12 12) (12 10)
(8 10) (8 4) (12 4) (12 2) (6 2) (6 6) (0 6)
Hub: (1 1), Terminal: (1 13)
The answer:
(1 1) (2 4) (4 4) (6 2) (12 2) (12 4) (10 6) (10 8) (12 10) (12 12)
(6 12) (4 10) (2 10) (1 13)
The input contains one or more data sets of the coordinates of the pillars, hubs and terminals. Each set begins with a line of an integer n (4n208), which is the number of the pillars of the study. The following lines contain the coordinates of pillars, five pairs of coordinates per line. After these lines comes one line that contains the coordinates of the hub (a_{x} a_{y}) and the terminal (b_{x} b_{y}).
The structure of one complete data set is as follows:(Input/output data do not use parentheses.)
n  
x_{1}  y_{1}  x_{2}  y_{2}  ...  x_{5}  y_{5} 
x_{6}  y_{6}  x_{7}  y_{7}  ...  x_{10}  y_{10} 
x_{11}  y_{11}  ...  
...  x_{n}  y_{n}  
a_{x}  a_{y}  b_{x}  b_{y} 
To make the situation simple, the coordinates of the pillars are all even integers, while those of
the hub and terminal are all odd. It is also known that the room size is less than 100 coordinate
units in both x and y directions and the cable length is shorter than 1000 coordinate units.
The input is terminated by a line having one 0 after the last set.
The sample input corresponds to Figures 1 and 5.
For each data set, print the sequence of the coordinates of turning points of the shortest cable with those of the hub at the beginning and those of the terminal at the end. Each line should contain five pairs of coordinates separated by a single space, except the last of these lines which may contain fewer than five. In each coordinate pair, x and y values should be separated also by a single space. The last coordinate of each line may be followed by a single space. The answer of each data set must be followed by a single empty line.
20 0 0 2 0 2 2 4 2 4 0 6 0 6 2 8 2 8 0 10 0 10 6 8 6 8 4 6 4 6 6 4 6 4 4 2 4 2 6 0 6 1 1 9 5 28 0 0 2 0 2 4 4 4 4 0 14 0 14 6 10 6 10 8 14 8 14 14 4 14 4 10 2 10 2 14 0 14 0 8 6 8 6 12 12 12 12 10 8 10 8 4 12 4 12 2 6 2 6 6 0 6 1 1 1 13 0
1 1 2 2 8 4 9 5 1 1 2 4 4 4 6 2 12 2 12 4 10 6 10 8 12 10 12 12 6 12 4 10 2 10 1 13 ______________________________________________________ 2153falseOne part of the new WAP portal is also a calculator computing expressions with very long numbers. To make the output look better, the result is formated the same way as is it usually used with manual calculations.
Your task is to write the core part of this calculator. Given two numbers and the requested operation, you are to compute the result and print it in the form specified below. With addition and subtraction, the numbers are written below each other. Multiplication is a little bit more complex: first of all, we make a partial result for every digit of one of the numbers, and then sum the results together.
Input
There is a single positive integer T on the first line of input. It stands for the number of expressions to follow. Each expression consists of a single line containing a positive integer number, an operator (one of +,  and *) and the second positive integer number. Every number has at most 500 digits. There are no spaces on the line. If the operation is subtraction, the second number is always lower than the first one. No number will begin with zero.
Output
For each expression, print two lines with two given numbers, the second number below the first one, last digits (representing unities) must be aligned in the same column. Put the operator right in front of the first digit of the second number. After the second number, there must be a horizontal line made of dashes ().
For each addition or subtraction, put the result right below the horizontal line, with last digit aligned to the last digit of both operands.
For each multiplication, multiply the first number by each digit of the second number. Put the partial results one below the other, starting with the product of the last digit of the second number. Each partial result should be aligned with the corresponding digit. That means the last digit of the partial product must be in the same column as the digit of the second number. No product may begin with any additional zeros. If a particular digit is zero, the product has exactly one digit  zero. If the second number has more than one digit, print another horizontal line under the partial results, and then print the sum of them.
There must be minimal number of spaces on the beginning of lines, with respect to other constraints. The horizontal line is always as long as necessary to reach the left and right end of both numbers (and operators) right below and above it. That means it begins in the same column where the leftmost digit or operator of that two lines (one below and one above) is. It ends in the column where is the rightmost digit of that two numbers. The line can be neither longer nor shorter than specified.
Print one blank line after each test case, including the last one.
Sample Input
4 12345+67890 324111 325*4405 1234*4Sample Output
12345 +67890  80235 324 111  213 325 *4405  1625 0 1300 1300  1431625 1234 *4  4936______________________________________________________ 2154false
ACM uses a new special technology of building its transceiver stations. This technology is called Modular Cuboid Architecture (MCA) and is covered by a patent of Lego company. All parts of the transceiver are shipped in unit blocks that have the form of cubes of exactly the same size. The cubes can be then connected to each other. The MCA is modular architecture, that means we can select preferred transceiver configuration and buy only those components we need.
The cubes must be always connected "facetoface", i.e. the whole side of one cube is connected to the whole side of another cube. One cube can be thus connected to at most six other units. The resulting equipment, consisting of unit cubes is called The Bulk in the communication technology slang.
Sometimes, an old and unneeded bulk is condemned, put into a storage place, and replaced with a new one. It was recently found that ACM has many of such old bulks that just occupy space and are no longer needed. The director has decided that all such bulks must be disassembled to single pieces to save some space. Unfortunately, there is no documentation for the old bulks and nobody knows the exact number of pieces that form them. You are to write a computer program that takes the bulk description and computes the number of unit cubes.
Each bulk is described by its faces (sides). A special Xray based machine was constructed that is able to localise all faces of the bulk in the space, even the inner faces, because the bulk can be partially hollow (it can contain empty spaces inside). But any bulk must be connected (i.e. it cannot drop into two pieces) and composed of whole unit cubes.
Input
There is a single positive integer T on the first line of input. It stands for the number of bulks to follow. Each bulk description begins with a line containing single positive integer F, 6 <= F <= 250, stating the number of faces. Then there are F lines, each containing one face description. All faces of the bulk are always listed, in any order. Any face may be divided into several distinct parts and described like if it was more faces. Faces do not overlap. Every face has one inner side and one outer side. No side can be "partially inner and partially outer".
Each face is described on a single line. The line begins with an integer number P stating the number of points that determine the face, 4 <= P <= 200. Then there are 3 x P numbers, coordinates of the points. Each point is described by three coordinates X,Y,Z (0 <= X,Y,Z <= 1000) separated by spaces. The points are separated from each other and from the number P by two space characters. These additional spaces were added to make the input more human readable. The face can be constructed by connecting the points in the specified order, plus connecting the last point with the first one.
The face is always composed of "unit squares", that means every edge runs either in X, Y or Zaxis direction. If we take any two neighbouring points X_{1},Y_{1},Z_{1} and X_{2},Y_{2},Z_{2}, then the points will always differ in exactly one of the three coordinates. I.e. it is either X_{1} <> X_{2}, or Y_{1} <> Y_{2}, or Z_{1} <> Z_{2}, other two coordinates are the same. Every face lies in an orthogonal plane, i.e. exactly one coordinate is always the same for all points of the face. The face outline will never touch nor cross itself.
Output
Your program must print a single line for every test case. The line must contain the sentence The bulk is composed of V units., where V is the volume of the bulk.
Sample Input
2 12 4 10 10 10 10 10 20 10 20 20 10 20 10 4 20 10 10 20 10 20 20 20 20 20 20 10 4 10 10 10 10 10 20 20 10 20 20 10 10 4 10 20 10 10 20 20 20 20 20 20 20 10 4 10 10 10 10 20 10 20 20 10 20 10 10 5 10 10 20 10 20 20 20 20 20 20 15 20 20 10 20 4 14 14 14 14 14 16 14 16 16 14 16 14 4 16 14 14 16 14 16 16 16 16 16 16 14 4 14 14 14 14 14 16 16 14 16 16 14 14 4 14 16 14 14 16 16 16 16 16 16 16 14 4 14 14 14 14 16 14 16 16 14 16 14 14 4 14 14 16 14 16 16 16 16 16 16 14 16 12 4 20 20 30 20 30 30 30 30 30 30 20 30 4 10 10 10 10 40 10 40 40 10 40 10 10 6 10 10 20 20 10 20 20 30 20 30 30 20 30 40 20 10 40 20 6 20 10 20 20 20 20 30 20 20 30 40 20 40 40 20 40 10 20 4 10 10 10 40 10 10 40 10 20 10 10 20 4 10 40 10 40 40 10 40 40 20 10 40 20 4 20 20 20 30 20 20 30 20 30 20 20 30 4 20 30 20 30 30 20 30 30 30 20 30 30 4 10 10 10 10 40 10 10 40 20 10 10 20 4 40 10 10 40 40 10 40 40 20 40 10 20 4 20 20 20 20 30 20 20 30 30 20 20 30 4 30 20 20 30 30 20 30 30 30 30 20 30Sample Output
The bulk is composed of 992 units. The bulk is composed of 10000 units.______________________________________________________ 2155false
You probably know those quizzes in Sunday magazines: given the sequence 1, 2, 3, 4, 5, what is the next number? Sometimes it is very easy to answer, sometimes it could be pretty hard. Because these "sequence problems" are very popular, ACM wants to implement them into the "Free Time" section of their new WAP portal.
ACM programmers have noticed that some of the quizzes can be solved by describing the sequence by polynomials. For example, the sequence 1, 2, 3, 4, 5 can be easily understood as a trivial polynomial. The next number is 6. But even more complex sequences, like 1, 2, 4, 7, 11, can be described by a polynomial. In this case, 1/2.n^{2}1/2.n+1 can be used. Note that even if the members of the sequence are integers, polynomial coefficients may be any real numbers.
Polynomial is an expression in the following form:
P(n) = a_{D}.n^{D}+a_{D1}.n^{D1}+...+a_{1}.n+a_{0}
. If a_{D} <> 0, the number D is called a degree of the polynomial. Note that constant function P(n) = C can be considered as polynomial of degree 0, and the zero function P(n) = 0 is usually defined to have degree 1.
Input
There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case consists of two lines. First line of each test case contains two integer numbers S and C separated by a single space, 1 <= S < 100, 1 <= C < 100, (S+C) <= 100. The first number, S, stands for the length of the given sequence, the second number, C is the amount of numbers you are to find to complete the sequence.
The second line of each test case contains S integer numbers X_{1}, X_{2}, ... X_{S} separated by a space. These numbers form the given sequence. The sequence can always be described by a polynomial P(n) such that for every i, X_{i} = P(i). Among these polynomials, we can find the polynomial P_{min} with the lowest possible degree. This polynomial should be used for completing the sequence.
Output
For every test case, your program must print a single line containing C integer numbers, separated by a space. These numbers are the values completing the sequence according to the polynomial of the lowest possible degree. In other words, you are to print values P_{min}(S+1), P_{min}(S+2), .... P_{min}(S+C).
It is guaranteed that the results P_{min}(S+i) will be nonnegative and will fit into the standard integer type.
Sample Input
4 6 3 1 2 3 4 5 6 8 2 1 2 4 7 11 16 22 29 10 2 1 1 1 1 1 1 1 1 1 2 1 10 3Sample Output
7 8 9 37 46 11 56 3 3 3 3 3 3 3 3 3 3______________________________________________________ 2156false
Building the GSM network is a very expensive and complex task. Moreover, after the Base Transceiver Stations (BTS) are built and working, we need to perform many various measurements to determine the state of the network, and propose effective improvements to be made.
The ACM technicians have a special equipment for measuring the strength of electromagnetic fields, the transceivers' power and quality of the signal. This equipment is packed into a huge knapsack and the technician must move with it from one BTS to another. Unfortunately, the knapsack have not enough memory for storing all of the measured values. It has a small cache only, that can store values for several seconds. Then the values must be transmitted to the BTS by an infrared connection (IRDA). The IRDA needs direct visibility between the technician and the BTS.
Your task is to find the path between two neighbouring BTSes such that at least one of those BTSes is always visible.
Input
There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case consists of a town description. For simplicity, a town is modelled as a rectangular grid of P x Q square fields. Each field is exactly 1 metre wide. For each field, a nonnegative integer Z_{i,j} is given, representing the height of the terrain in that place, in metres. That means the town model is made of cubes, each of them being either solid or empty. There are no "half solid" cubes.
The first line of each test case contains two integer numbers P and Q, separated by a single space, 1 <= P,Q <= 200. Then there are P lines each containing Q integer numbers separated by a space. These numbers are Z_{i,j}, where 1 <= i <= P, 1 <= j <= Q and 0 <= Z_{i,j} <= 5000. After the terrain description, there are four numbers R_{1}, C_{1}, R_{2}, C_{2} on the last line of each test case. These numbers represent position of two BTSes, 1 <= R_{1},R_{2} <= P, 1 <= C_{1},C_{2} <= Q. The first coordinate (R) determines the row of the town, the second coordinate determines the column.
The technician is moving in steps (steps stands for Standard Technician's Elementary Positional Shift). Each step is made between two neighbouring square fields. That means the step is always in North, South, West or East direction. It is not possible to move diagonally. The step between two fields A and B (step from A to B) is allowed only if the height of the terrain in the field B is not very different from the height in the field A. The technician can climb at most 1 metre up or descend at most 3 metres down in a single step.
At the end of each step, at least one of the two BTSes must be visible. However, there can be some point "in the middle of the step" where no BTS is visible. This is OK and the data is handled by the cache. The BTS is considered visible, if there is a direct visibility between the unit cube just above the terrain on the BTSes coordinates and the cube just above the terrain on the square field, where the technician is. Direct visibility between two cubes means that the line connecting the centres of the two cubes does not intersect any solid cube. However, the line can touch any number of solid cubes. In other words, consider both the BTS and the technician being points exactly half metre above the surface and in the centre of the appropriate square field.
Note that the IRDA beam can go between two cubes that touch each other by their edge, although there is no space between them. It is because such a beam touches both of these two cubes but does not intersect any of them. See the last test case of the sample input for an example of such a situation.
Output
You are to find the shortest possible path meeting the above criteria. All steps must be done between neighbouring fields, the terrain must not elevate or descend too much, and at the end of each step, at least one BTS must be visible.
For each test case, print one line containing the sentence The shortest path is M steps long., where M is the number of steps that must be made. If there is no such path, output the sentence Mission impossible!.
Sample Input
4 5 5 8 7 6 5 4 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 5 1 5 8 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 9 9 9 9 9 9 9 2 2 2 2 2 2 2 2 2 1 2 5 1 5 8 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 9 9 9 9 9 9 9 2 2 2 2 2 2 2 2 2 1 5 5 1 6 12 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5 5 9 5 5 5 5 5 5 5 5 9 1 5 5 5 5 5 5 5 5 5 5 5 9 5 5 5 5 5 5 5 5 5 5 5 9 5 5 5 5 5 5 5 5 5 6 1 3 12Sample Output
The shortest path is 10 steps long. Mission impossible! The shortest path is 14 steps long. The shortest path is 18 steps long.______________________________________________________ 2157false
The most important activity of ACM is the GSM network. As the mobile phone operator, ACM must build its own transmitting stations. It is very important to compute the exact behaviour of electromagnetic waves. Unfortunately, prediction of electromagnetic fields is a very complex task and the formulas describing them are very long and hardtoread. For example, below are the Maxwell's Equations describing the basic laws of electrical engineering.
ACM has designed its own computer system that can make some field computations and produce results in the form of mathematic expressions. Unfortunately, by generating the expression in several steps, there are always some unneeded parentheses inside the expression. Your task is to take these partial results and make them "nice" by removing all unnecessary parentheses.
There is a single positive integer T on the first line of input. It stands for the number of expressions to follow. Each expression consists of a single line containing only lowercase letters, operators (+, , *, /) and parentheses (( and )). The letters are variables that can have any value, operators and parentheses have their usual meaning. Multiplication and division have higher priority then subtraction and addition. All operations with the same priority are computed from left to right (operators are leftassociative). There are no spaces inside the expressions. No input line contains more than 250 characters.
Print a single line for every expression. The line must contain the same expression with unneeded parentheses removed. You must remove as many parentheses as possible without changing the semantics of the expression. The semantics of the expression is considered the same if and only if any of the following conditions hold:
You cannot use any other laws, namely you cannot swap left and right operands and you cannot replace "a(bc)" with "ab+c".
8 (a+(b*c)) ((a+b)*c) (a*(b*c)) (a*(b/c)*d) ((a/(b/c))/d) ((x)) (a+b)(cd)(e/f) (a+b)+(cd)(e+f)
a+b*c (a+b)*c a*b*c a*b/c*d a/(b/c)/d x a+b(cd)e/f a+b+cd(e+f)
______________________________________________________ 2158false
The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically.
ACM technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called "Travelling Salesman Problem" and it is very hard to solve. If we have N BTSes to be visited, we can visit them in any order, giving us N! possibilities to examine. The function expressing that number is called factorial and can be computed as a product 1.2.3.4....N. The number is very high even for a relatively small N.
The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. So they started to study behaviour of the factorial function.
For example, they defined the function Z. For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!. They noticed that this function never decreases. If we have two numbers N_{1}<N_{2}, then Z(N_{1}) <= Z(N_{2}). It is because we can never "lose" any trailing zero by multiplying by any positive number. We can only get new and new zeros. The function Z is very interesting, so we need a computer program that can determine its value efficiently.
There is a single positive integer T on the first line of input. It stands for the number of numbers to follow. Then there is T lines, each containing exactly one positive integer number N, 1 <= N <= 1000000000.
For every number N, output a single line containing the single nonnegative integer Z(N).
6 3 60 100 1024 23456 8735373
0 14 24 253 5861 2183837
______________________________________________________ 2159false
If you want to buy a new cellular phone, there are many various types to choose from. To decide which one is the best for you, you have to consider several important things: its size and weight, battery capacity, WAP support, colour, price. One of the most important things is also the list of games the phone provides. Nokia is one of the most successful phone makers because of its famous Snake and Snake II. ACM wants to make and sell its own phone and they need to program several games for it. One of them is MasterMind, the famous board logical game.
The game is played between two players. One of them chooses a secret code consisting of P ordered pins, each of them having one of the predefined set of C colours. The goal of the second player is to guess that secret sequence of colours. Some colours may not appear in the code, some colours may appear more than once.
The player makes guesses, which are formed in the same way as the secret code. After each guess, he/she is provided with an information on how successful the guess was. This feedback is called a hint. Each hint consists of B black points and W white points. The black point stands for every pin that was guessed right, i.e. the right colour was put on the right position. The white point means right colour but on the wrong position. For example, if the secret code is "white, yellow, red, blue, white" and the guess was "white, red, white, white, blue", the hint would consist of one black point (for the white on the first position) and three white points (for the other white, red and blue colours). The goal is to guess the sequence with the minimal number of hints.
The new ACM phone should have the possibility to play both roles. It can make the secret code and give hints, but it can also make its own guesses. Your goal is to write a program for the latter case, that means a program that makes MasterMind guesses.
There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case describes one game situation and you are to make a guess. On the first line of each test case, there are three integer numbers, P, C and M. P ( 1 <= P <= 10) is the number of pins, C (1 <= C <= 100) is the number of colours, and M (1 <= M <= 100) is the number of already played guesses.
Then there are 2 x M lines, two lines for every guess. At the first line of each guess, there are P integer numbers representing colours of the guess. Each colour is represented by a number G_{i}, 1 <= G_{i} <= C. The second line contains two integer numbers, B and W, stating for the number of black and white points given by the corresponding hint.
Let's have a secret code S_{1}, S_{2}, ... S_{P} and the guess G_{1}, G_{2}, ... G_{P}. Then we can make a set H containing pairs of numbers (I,J) such that S_{I} = G_{J}, and that any number can appear at most once on the first position and at most once on the second position. That means for every two different pairs from that set, (I_{1},J_{1}) and (I_{2},J_{2}), we have I_{1} <> I_{2} and J_{1} <> J_{2}. Then we denote B(H) the number of pairs in the set, that meet the condition I = J, and W(H) the number of pairs with I <> J.
We define an ordering of every two possible sets H_{1} and H_{2}. Let's say H_{1} <= H_{2} if and only if one of the following holds:
Then we can find a maximal set H_{max} according to this ordering. The numbers B(H_{max}) and W(H_{max}) are the black and white points for that hint.
For every test case, print the line containing P numbers representing P colours of the next guess. Your guess must be valid according to all previous guesses and hints. The guess is valid if the sequence could be a secret code, i.e. the sequence was not eliminated by previous guesses and hints.
If there is no valid guess possible, output the sentence You are cheating!. If there are more valid guesses, output the one that is lexicographically smallest. I.e. find such guess G that for every other valid guess V there exists such a number I that:
3 4 3 2 1 2 3 2 1 1 2 1 3 2 1 1 4 6 2 3 3 3 3 3 0 4 4 4 4 2 0 8 9 3 1 2 3 4 5 6 7 8 0 0 2 3 4 5 6 7 8 9 1 0 3 4 5 6 7 8 9 9 2 0
1 1 1 3 You are cheating! 9 9 9 9 9 9 9 9
______________________________________________________ 2160false
Every customer sometimes needs help with new and unusual products. Therefore, hotline service is very important for every company. We need a single phone number where the customer can always find a friendly voice ready to help with anything. On the other hand, many people are needed to serve as hotline operators, and human resources are always very expensive. Moreover, it is not easy to pretend "friendly voice" at 4am and explain to a drunken man that you are really unable to give him the number to House of Parliament. It was also found that some of the questions repeat very often and it is very annoying to answer them again and again.
ACM is a modern company, wanting to solve its hotline problem. They want to decrease the number of human operators by creating a complex software system that would be able to answer most common questions. The customer's voice is analysed by a special Voice Recognition Module (VRM) and converted to a plain text. The text is then taken by an Artificial Automatic Adaptive Answering Algorithm (AAAAA). The most common questions are recognised and answered automatically. The replies are then converted to a sound by TexttoSpeech Module (TTS).
You are to write the AAAAA module. Because your algorithm should be adaptive, it has no explicit knowledge base. But it must be able to listen to sentences in English and remember the mentioned facts. Whenever the question is asked about such a fact, the system has to answer it properly. The VRM and TTS modules are already implemented, so the input and output of AAAAA will be in the text form.
There is a single positive integer T on the first line of input. It stands for the number of dialogues to follow. Each dialogue consists of zero or more lines, each of them containing one sentence: either statement or question. The statement ends with a dot character (.), the question ends with a question mark (?). No statement will appear more than once, however the questions can be repeated. There is one extra line after each dialogue. That line ends with an exclamation mark (!).
Sentences can contain words, spaces and punctuation characters (such as commas, colons, semicolons etc.). All words contain only letters of English alphabet and are casesensitive. That means the same word is always written the same way, usually in lowercase. Acronyms, names and some other words can begin with capital letters. For simplicity, all sentences begin with a lowercase letter. Only if the first word should be written with a capital, the sentence begins with a capital letter. There are no unneeded spaces between words. No line will have more than 100 characters. There will be at most 100 statements per each test case.
Each statement has one of the following two forms (
denotes a space):
subject
predicate[s] [
object] .
subject
don'tdoesn't
predicate [
object]
.
The square brackets mark an optional part, the vertical line two possible variants. Subject is a single word, noun or pronoun in singular. Predicate is a verb (single word) denoting some activity. Object can be any text. Object does not contain any dots. Any pair "verb + object" determines unique activity. The same verb with different objects makes different independent activities, i.e. the different and independent meaning of the sentence. Sentence without any object can be considered as sentence with an empty object. The verb without an object has different and independent meaning than the same verb with any nonempty object.
The first variant of sentence denotes a positive statement. The word "predicate[s]" means verb that matches the subject of the sentence. If the subject is "I" or "you", the verb has the same form as the infinitive. With any other subject, the letter "s" is appended on the end of the verb. Assume there are no irregular verbs.
The second variant is a negative statement. Verb "don't" or "doesn't" must also match the subject. The form "don't" is used with either "I" or "you", "doesn't" is used in any other case.
A special generic subject "everybody" can be used. It means the activity holds for any subject. Other special subject is "nobody". Such sentence also holds for any subject, but its meaning is negative. Both of these generic subjects can be used with the first variant only (without "doesn't"). The sentence "nobody likes something" is exactly equal to "everybody doesn't like something", except the latter form will never occur in the input.
Each question has one of the following three forms:
The word "dodoes" always matches the subject ("do I?", "do you?", "does any other subject?"). In the second type of question, predicate always matches the word "who", i.e. the "s" is always appended. Generic subjects cannot be used in questions.
For each dialogue, your program must output the line Dialogue #D:, where D is the sequence number of dialogue, starting with 1. Then print exactly three lines for every question: the first line repeats the question, the second line contains the answer, and the third line is empty. Print nothing for statements. After each dialogue, print the same line with an exclamation mark that was in the input. Then print one extra empty line. Empty line contains a newline character only.
The answer must be properly formated to be accepted by a TTS module. Only the statements appearing in the input before the answer are used for the corresponding reply. If there is any contradiction among statements, the reply is always I am abroad.. If the question and statements consider the special subject "you", it must be replaced with "I" in the answer. If the question considers special subject "I", it must be replaced with "you" in the answer. The verb must always match the subject of the sentence. The exact form of the correct answer depends on the type of question.
If there is any positive statement about the mentioned subject (or
generic subject "everybody"), predicate and object, the answer
is:
yes,
subject
predicate[s] [
object] .
If there is any negative statement about the mentioned subject (or
generic subject "nobody"), predicate and object, the answer is:
no,
subject
don'tdoesn't
predicate [
object] .
Otherwise, the answer is: maybe.
Subject in the answer is always the same subject as the subject of the question.
If there is a positive statement considering any subject, the
specified predicate and object, the answer is:
subject
predicate[s] [
object] .
If two or more subjects match the activity, replace the subject in the
answer with enumeration of all such subjects, in the same order as the
corresponding statements have appeared in the input. Subjects are
separated with comma and space, last two subjects are separated with the
word "and". If "everybody" belongs to the group of
enumerated subjects, do not enumerate subjects, and print
"everybody" only. If the enumeration contains at least two
subjects, the predicate matches the plural subject (i.e. verb is without
trailing "s"), otherwise it matches the only subject.
subject1 ,
subject2 and
subject3 predicate [
object] .
If there is a negative statement considering the generic subject
"nobody", the specified predicate and object, the answer is:
nobody
predicates [
object] .
Otherwise, the answer is: I don't know.
If there are one or more sentences (both positive and negative)
considering the specified subject (or a generic subject
"everybody" or "nobody"), all verbs and objects from
such sentences must be included in a reply in the same order as the
corresponding sentences have appeared in the input. No verbobject pair
can be included more than once (the eventual second appearance must be
skipped). The verbobject pairs are separated by a comma followed by
a space, the last verb is separated by a comma and the word
"and". Please note the comma is printed here although there was
no comma when separating the subjects in the previous type of answer (see
above). The negative answers have the same form as the statements, that
means the verb "don't" or "doesn't" is used:
subject [
don'tdoesn't]
predicate1[s] [
object1] ,
[
don'tdoesn't]
predicate2[s] [
object2] ,
and [
don'tdoesn't]
predicate3[s] [
object3] .
subject [
don'tdoesn't]
predicate1[s] [
object1] ,
and [
don'tdoesn't]
predicate2[s] [
object2] .
subject [
don'tdoesn't]
predicate[s] [
object] .
Otherwise, the answer is: I don't know.
1 I like hotdogs. nobody likes to work. everybody smiles. what do I do? who smiles? what do you do? does Joe smile? do I like to work? everybody hurts sometimes. who walks there? Michal walks there. who walks there? what does Michal do? do you understand? nobody walks there. do you understand now? bye!
Dialogue #1: what do I do? you like hotdogs, don't like to work, and smile. who smiles? everybody smiles. what do you do? I don't like to work, and smile. does Joe smile? yes, Joe smiles. do I like to work? no, you don't like to work. who walks there? I don't know. who walks there? Michal walks there. what does Michal do? Michal doesn't like to work, smiles, hurts sometimes, and walks there. do you understand? maybe. do you understand now? I am abroad. bye!
______________________________________________________ 2161false
Most of you have probably tried to type an SMS message on the keypad of a cellular phone. It is sometimes very annoying to write longer messages, because one key must be usually pressed several times to produce a single letter. It is due to a low number of keys on the keypad. Typical phone has twelve keys only (and maybe some other control keys that are not used for typing). Moreover, only eight keys are used for typing 26 letters of an English alphabet. The standard assignment of letters on the keypad is shown in the left picture:
There are 3 or 4 letters assigned to each key. If you want the first letter of any group, you press that key once. If you want the second letter, you have to press the key twice. For other letters, the key must be pressed three or four times. The authors of the keyboard did not try to optimise the layout for minimal number of keystrokes. Instead, they preferred the even distribution of letters among the keys. Unfortunately, some letters are more frequent than others. Some of these frequent letters are placed on the third or even fourth place on the standard keyboard. For example, S is a very common letter in an English alphabet, and we need four keystrokes to type it. If the assignment of characters was like in the right picture, the keyboard would be much more comfortable for typing average English texts.
ACM have decided to put an optimised version of the keyboard on its new cellular phone. Now they need a computer program that will find an optimal layout for the given letter frequency. We need to preserve alphabetical order of letters, because the user would be confused if the letters were mixed. But we can assign any number of letters to a single key.
There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case begins with a line containing two integers K, L (1 <= K <= L <= 90) separated by a single space. K is the number of keys, L is the number of letters to be mapped onto those keys. Then there are two lines. The first one contains exactly K characters each representing a name of one key. The second line contains exactly L characters representing names of letters of an alphabet. Keys and letters are represented by digits, letters (which are casesensitive), or any punctuation characters (ASCII code between 33 and 126 inclusively). No two keys have the same character, no two letters are the same. However, the name of a letter can be used also as a name for a key.
After those two lines, there are exactly L lines each containing exactly one positive integer F_{1}, F_{2}, ... F_{L}. These numbers determine the frequency of every letter, starting with the first one and continuing with the others sequentially. The higher number means the more common letter. No frequency will be higher than 100000.
Find an optimal keyboard for each test case. Optimal keyboard is such that has the lowest "price" for typing average text. The price is determined as the sum of the prices of each letter. The price of a letter is a product of the letter frequency (F_{i}) and its position on the key. The order of letters cannot be changed, they must be grouped in the given order.
If there are more solutions with the same price, we will try to maximise the number of letters assigned to the last key, then to the one before the last one etc.
More formally, you are to find a sequence P_{1}, P_{2}, ... P_{L} representing the position of every letter on a particular key. The sequence must meet following conditions:
1 8 26 23456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ 3371 589 1575 1614 6212 971 773 1904 2989 123 209 1588 1513 2996 3269 1080 121 2726 3083 4368 1334 518 752 427 733 871
Keypad #1: 2: ABCD 3: EFG 4: HIJK 5: LM 6: NOPQ 7: RS 8: TUV 9: WXYZ
______________________________________________________ 2162false
A Strange Tree (Stree) over the variable set X_{n}={x_{1}, ..., x_{n}} is a complete binary tree representing a Boolean function f: {0,1}^n > {0,1}. Each of the Stree's nodes has a depth, defined as the number of nodes in the path from the root to itself minus 1 (so the root has depth 0). The depth of any node in an Stree is at most n. The nodes with depth less than n are called nonterminal nodes, each having two children: the right child and the left child. Each nonterminal node is labeled with some variable x_{i} from the variable set X_{n}. All nonterminal nodes with the same depth are labeled with the same variable, and nonterminal nodes with different depth are labeled with different variables. So, there is a unique variable x_{i0} corresponding to the root, a unique variable x_{i1} corresponding to the nodes with depth 1, and so on. The sequence of the variables x_{i0}, x_{i1}, ..., x_{in1 }is called the variable ordering. The nodes having depth n are called terminal nodes. They have no children and are labeled with either 0 or 1. Note that the variable ordering and the distribution of 0's and 1's on terminal nodes are sufficient to completely describe an Stree.
As stated earlier, each Stree represents a Boolean function f. If you have an Stree and values for the variables x_{1}, ..., x_{n}, then it is quite simple to evaluate f(x_{1}, ..., x_{n}): Start at the root and repeat the following steps: if the node you are at is labeled with a variable x_{i}, then depending on whether the value of x_{i} is 1 or 0, you go to its right or left child, respectively. Once you reach a terminal node, its label gives the value of the function.
x1 x3 / \ / \ / \ / \ x2 x2 x1 x1 / \ / \ / \ / \ x3 x3 x3 x3 x2 x2 x2 x2 / \ / \ / \ / \ / \ / \ / \ / \ 0 0 0 0 0 1 1 1 0 0 0 1 0 0 1 1
Fig. 1. Strees for the function x_{1} and (x_{2} or x_{3})
In the picture, the two Strees represent the same Boolean function:
f(x_{1}, x_{2}, x_{3})=x_{1} and (x_{2} or x_{3})
For the left tree, the variable ordering is x_{1}, x_{2}, x_{3}, and for the right tree it is x_{3}, x_{1}, x_{2}. The values of the variables x_{1}, ..., x_{n}, are given as a Variable Value Assignment (VVA) (x_{1}=b_{1}, x_{2}=b_{2}, ..., x_{n}=b_{n}) with b_{1}, b_{2}, ... b_{n} in {0,1}. For instance, (x_{1}=1, x_{2}=1, x_{3}=0) would be a VVA for n=3, resulting, for the sample function above, in the value f(1, 1, 0)=1 and (1 or 0)=1.Your task is to write a program which takes an Stree and some VVAs and computes f(x_{1}, ..., x_{n}) as described above.
The input file contains the description of several Strees with associated VVAs which you have to process. Each description begins with a line containing a single integer n; 1 <= n <= 7, the depth of the Stree. This is followed by a line describing the variable ordering of the Stree. The format of that line is x_{i1} x_{i2} ... x_{i}n. (There will be exactly n different single spaceseparated strings). So, for n=3 and the variable ordering x_{3}, x_{1}, x_{2}, this line would look as follows
x3 x1 x2
In the next line the distribution of 0's and 1's over the terminal nodes is given. There will be exactly 2^n characters (each of which can be 0 or 1), followed by the newline character. The characters are given in the order in which they appear in the Stree, the first character corresponds to the leftmost terminal node of the Stree, the last one to its rightmost terminal node.
The next line contains a single integer m, the number of VVAs, followed by m lines describing them. Each of the m lines contains exactly n characters (each of which can be 0 or 1), followed by a newline character. Regardless of the variable ordering of the Stree, the first character always describes the value of x_{1}, the second character describes the value of x_{2}, and so on. So, the line
110
corresponds to the VVA (x_{1}=1, x_{2}=1, x_{3}=0).
The input is terminated by a test case starting with n=0. This test case should not be processed.
For each Stree, output the line "STree #j", where j is the number of the Stree. Then print a line that contains the value of f(x_{1}, x_{2}, ..., x_{n}) for each of the given m VVAs, where f is the function defined by the Stree. Output a blank line after each test case.
3 x1 x2 x3 00000111 4 000 010 111 110 3 x3 x1 x2 00010011 4 000 010 111 110 0
STree #1 0011 STree #2 0011
______________________________________________________ 2163false
Some led systems display characters as a combination of lightlines, much like digital calculators do. Suppose we have one of such led systems, in which each letter of the standard English alphabet is constructed combining some of ten possible lightlines, numbered as below:
For instance, the letter A is shown using the lines 1,2,3,4,5 and 7. With these few lines it is not possible, of course, to show all the 26 letters with their natural shapes. A complete list of the letters of our system is appended at the end.
You have to solve the problem of decoding a combination of numbers (representing lightlines) in the form of the respective letter, to form a whole word or phrase. As input you have a string of letters and/or numbers, and as output you must show only the letters.
The input file begins with a line containing a single integer N, that indicates the number of input examples, followed by N lines, each one representing an input phrase. Each input phrase consists of uppercase letters, blank spaces and/or digits. In the case of digits, their combination must form valid led letters. Each letter is coded as a combination of numbers, ordered in the form 1,2,3,4,5,6,7,8,9,0. A zero (0) that is not part of a valid letter code, is interpreted as a blank space. You may assume that no invalid codes are entered, and that the system does not allow ambiguity between two letter codes.
The output file consists of N lines (one for each input string) with the form:
Phrase 1: ..... Phrase 2: .....
where the dots are, of course, the result of the decoding process. The alphabetic letters and blank spaces must not be decoded at all: only the numbers must be converted to the corresponding led letters.
3 HELL1235670WO1234591561580 PROGRAMMING037124670C123567123567156 AND MORE037124903735790278134573712467045612356735792781245612467278
Phrase 1: HELLO WORLD Phrase 2: PROGRAMMING IS COOL Phrase 3: AND MORE IF IN THIS CONTEST
A local cable network is planning to expand their services to a neighboring city. For that, a transmission center is being built and a cable net connecting the new clients has to be installed. Each client has to be connected to the center in the cable net.
The network organized a survey and has now the addresses of all potential clients. Also it has an estimate on the cost of installing each cable link through the city.
The network board of directors has decided to offer the following initial subscription package: Each new client will pay a fixed subscription fee and will get the first three months of service for free. This ensures a potential initial capital for building the cable net, which is simply the number of potential clients (according to the survey) multiplied by the subscription fee.
The decision on what links to build in this first phase will be done according to the following. A set of links induces a loss in the potential initial capital, defined as l + (t * d), where l is the cost of installing the links in the set, t is the subscription fee and d is the number of potential clients that are not connected to the center by this set of links. The board of directors decided they will build a set of links that induces a loss as small as possible in the potential initial capital.
Your job is to write a program to compute the minimum possible loss in the potential initial capital. For that, you are given the location of each potential client as well as the center location. Also, you are given the costs of all possible net links and the value of the subscription fee.
The input file contains the description of several instances. An instance with n=0 indicates the end of the input. Your program should not process this instance.
The first line of the file, contains two positive integers: n (0 <= n <= 20) representing the number of potential clients and t representing the subscription fee. Each potential client is identified by a number between 1 and n while the center is identified by 0. Next, there is a line for each i from 0 to n1. In line i there is a list of ni positive integers. Each integer, say the jth one, represents the cost of installing a link between i and j.
For each instance, your program should print three lines; the first contains "Cable Net #j", where j is the number of the instance; in the second line, it should print the potential initial capital for that instance and in the third line, the value of the minimum possible loss in the potential initial capital for that instance. Your program should also print a blank line after the output of each instance.
5 10 5 17 2 3 23 9 6 1 19 14 5 13 19 21 40 3 1 5 3 23 1 19 14 0 1
Cable Net #1 50 21 Cable Net #2 3 3
______________________________________________________ 2165false
The Air Force has a special team devoted to destroying bridges. This team is composed of several planes which over the targeted bridge one after another. Each of these planes carries one bomb, which the pilot drops at a given location in the bridge. The aim of the team is to split the bridge in two, so that no one can cross it.
Unfortunately, bombs are not completely accurate. As a result, even though missions are planned in advance, the exact location where the bombs actually fall may be different than planned. Still, the Air Force keeps his original plan untouched except for the last plane, which may have to act differently.
Each bomb that is dropped on the bridge leaves a hole that, viewed from above, has the shape of a circle, its radius depending on the power of the bomb. A bomb of size s leaves a hole of radius s. Your task is to determine the plan for the last plane, that is, the minimum bomb size and the position where the last plane should drop the bomb so that, if everything goes well, the bridge is split in two.
The first line contains a positive integer n, representing the number of instances of the problem contained on the input file.
Each instance is represented by three positive integers w, l and b, which denote the width and length of the bridge and the amount of bombs dropped on the bridge. Then come b lines, each containing integers x, y and r (x, y >= 0, r > 0) which denote the coordinates of the center and the radius of the holes left by the b bombs. Coordinate (0,0) is the lowerleft corner of the bridge (viewed from above), assuming that the bridge has width parallel to the x axis and length parallel to the y axis.
Your program must produce one output line for each instance. This line contains an integer representing the minimum bomb size you need to split the bridge in two, or the words Bridge already split if the bridge is already split by the bombs that have been dropped. The bridge is considered to be split if the two ends of the bridge are disconnected (except perhaps for a finite number of points). Remember that a bomb of size s leaves a hole of radius s.
3 100 1000 2 15 100 20 90 100 30 100 1000 1 50 100 40 100 1000 2 25 500 25 75 500 25
13 50 Bridge already split
______________________________________________________ 2166false
You have three jars containing water. Each jar has associated a capacity indicating the maximum amount of water it can contain. Your wish is to have a certain amount of water in each jar. The initial content of each jar, its capacity, and the desired content, are all non negative integers; in addition, the capacities are between 1 and 150. You have nothing but the jars to help you in achieving your goal. So the only way to obtain the desired content in each jar is to make a sequence of movements of water. In a movement of water you pour a certain amount of water from one jar to another jar. We call the first jar source and the second jar destination. While moving water two situations can occur: If the current content of the source jar is not enough to complete the capacity of the destination jar, then all the water contained in the source jar is moved to the destination jar; otherwise, only the exact amount of water needed to complete the destination jar is moved from the source jar. Under no circumstances you can use additional water or throw away water. Your task is to determine the minimum number of movements required to obtain the desired amount of water in each jar.
The input file contains a certain number of test cases for this problem. Each test case is given in a single line containing nine values c_{1}, c_{2}, c_{3}, a_{1}, a_{2}, a_{3}, b_{1}, b_{2}, b_{3}; these values are separated by an arbitrary number of blank spaces. The value c_{i} is the capacity of the ith jar, a_{i} is its initial content, and b_{i} is the desired content for the jar. In the last line of the file c_{1} has value equal to 0; this line should not be processed.
For each test case in the input file, the output file must contain a line with the minimum number of movements required to obtain the desired content in each jar. If for a given test case there is no solution, you must write the value 1 instead of the number of movements.
5 4 1 1 0 1 0 2 0 5 4 1 1 0 1 0 3 0 5 4 1 1 0 1 0 0 2 5 4 1 1 0 1 1 0 1 5 4 1 0 4 0 3 0 1 0 1 1 0 0 0 0 0 0
2 1 1 0 2 10
______________________________________________________ 2167false
Piet Mondrian (18721944) was one of the best abstract artists of the century. His simple yet elegant designs were intentionally restricted to use only straight lines and a few colors. His artwork reflects an idealized view of reality, one which has perfect harmony and balance.
Armando, a Latin American businessman, wants to create and sell fake Mondrian pictures. Since Mondrian's designs are based on a few simple rules, he hopes to build a machine that can massproduce different Mondrian pictures and sell them as originals.
Mondrian's rules are very simple:
1. only black, white, red, blue and yellow colors can be used.
2. the painting can only contain rectangles, with sides parallel to the borders of the canvas. Lines that are not part of the border of a rectangle are not allowed. The following four examples do not fulfill this rule:
The topleft painting contains a shape that is not a rectangle (the shape that is outside the central square). In the topright painting every shape is a rectangle, but there are lines that are not part of the border of any rectangle. Bottomleft painting contains a shape that is not a rectangle (the inverted L). Bottomright painting contains a line that is not part of the border of any rectangle. In the figure we also include a real (well, sort of) Mondrian (Composition with red, yellow, and blue, 1928).
3. Borders of the rectangles can only be painted in black. Rectangles can only be painted in white, red, blue or yellow. The borders of the canvas are considered to be already painted in black.
4. Two adjacent rectangles (that is, two rectangles that share a segment of their borders) cannot have the same color, unless they are painted in white.
The machine Armando has devised receives a set of instructions to draw the painting. Your task is to program an algorithm that will tell (before the machine begins to perform Armando's instructions) whether these instructions correspond to a picture that fulfills Mondrian's rules, and how much paint he will need.
The input file contains a set of test cases. Each test case is described in several lines, and contains Armando's instructions for one painting. There are two types of instructions: instructions that indicate the drawing of a line, and instructions that indicate the painting of a rectangle. Each test case of the input file starts with a line containing four integer values w, h, n, m. The values w and h represent the width and height of the canvas, respectively; these values are between 1 and 10000. The value n is the number of instructions for drawing lines, while m is the number of instructions for painting rectangles; these values are between 0 and 1000. The test case continues with n lines containing the instructions for drawing lines, each instruction in a separate line of the file. Each instruction consists of four integer values x_{1}, x_{2}, x_{3} and x_{4}, where (x_{1}, x_{2}) and (x_{3}, x_{4}) are the coordinates of the end points of the line. Lines are always horizontal or vertical. The lower left corner of the canvas has coordinates (0,0). Instructions can result in a line or part of a line being drawn more than once. The test case ends with m lines containing the instructions for painting rectangles, each one in a separate line of the input file. Each instruction specifies two integer values x and y, as well as a letter c in the set {r, b, y} (r means red, b is blue and y is yellow). The instruction indicates the machine to paint the rectangle containing the point with coordinates (x; y) with color c. All rectangles not painted with a color in this set are assumed to be painted in white. The input file ends with a test case in which w has a value of 0; this test case should not be processed. Every pair of consecutive values in a same line of the input file is separated by an arbitrary number of blank spaces.
Your program must produce one output line for each test case. If the instructions follow Mondrian's rules, you must write the line Mondrian r b y, where r, b and y are total areas painted in red, blue and yellow, respectively. Otherwise, you must write the line Error!.
100 100 3 3 0 50 60 50 20 50 100 50 50 0 50 100 25 25 r 75 75 r 25 75 y 610 987 2 3 0 50 305 50 305 0 305 987 1 1 r 1 400 r 400 100 y 1000 1000 3 2 0 200 500 200 500 0 500 400 500 400 1000 400 200 800 r 700 200 y 0 0 0 0
Mondrian: 5000 0 2500 Error! Error!
______________________________________________________ 2168false
The importance of postfix and prefix notation in parsing arithmetic expressions is that these notations are completely free of parentheses. Consequently, an expression in postfix (or prefix) form is crucial because having a unique form for an expression greatly simplifies its evaluation. But we humans prefer to read and evaluate an infix expression especially when it is parenthesized.
We would like to try the conversion from the postfix format to the parenthesized infix format for expression written in some functional language. The language will consist of the unary function INV and the binary functions ADD and MUL.
The input shall consist of several cases. Each case will be represented on a separate line. The number of cases will be given in the first line of the input.
For each input case, the converted expression should be on a separate line, and should have a space after each comma.
2 2 3 Add Inv 6 10 Mul Mul 100 1000 MUL 10 ADD INV
Mul ( Inv (Add (2, 3)), Mul (6, 10)) Inv ( Add (10, Mul (100, 1000)))
______________________________________________________ 2169false
This problem is about right justification of the text. By that we mean that the printed form of the text is such that the right margin is aligned for all lines in the output. This task is normally achieved by first attempting to split words across lines, and then by leaving a certain amount of spaces between words.
For this problem, assume that words are not to be split between lines and that each line is to be both left and right justified, except for the last line of text. Any extra blank characters which are required in the justification of the text are to be distributed as uniformly as possible between the words of a line. Furthermore, we assume that there are no paragraphs and that pagination and indentation are not required. Finally, each word in the input text is separated from every other word by a blank, and each punctuation symbol is followed by a blank.
For the output, assume 50 characters per line.
Sultan Qaboos university is a young university compared to universities found in the ArabianGulf region. However, it has an excellent reputation in the region. The university enjoys solid infrastructure, stable academic platforms, and state of the art facilities. The university includes six colleges, four centers, three libraries, and a hospital. A new college of information technology seems to be on the horizon, and may be announced any time.
Sultan Qaboos university is a young university compared to universities found in the ArabianGulf region. However, it has an excellent reputation in the region. The university enjoys solid infrastructure, stable academic platforms, and state of the art facilities. The university includes six colleges, four centers, three libraries, and a hospital. A new college of information technology seems to be on the horizon, and may be announced any time.
______________________________________________________ 2170false
"Logic World" is a company that produces systems with extensive use of bitwise operators. Before hiring engineers, the company tests their ability to write programs that manipulate bitstrings to evaluate both their programming skills and their mastery of the bitwise operators: OR, AND, NOR, NAND and XNOR. The test gives three bitstrings of length 40 represented in hexadecimal, and five operations to be performed on these bitstrings. Given the strings S1, S2 and S3, the operations to be performed will be: S1 AND S2, S2 OR S3, S1 AND (S2 OR S3), S1 NAND S2 NOR S3, (S1 NOR S2) XNOR (S2 NOR S3)
Challenge yourself by taking this test and see whether you would be hired by ``Logic World"
The input data consists of a set of cases terminated by a case of only X's. Each case is made of 3 bitstrings separated by a comma and a space.
For each case, results of the five operations should be given as shown in the sample output. Leave a blank line after each case.
FFFFFF4444, 222F0FFF11, AABBCCDDEE XXXXXXXXXX, XXXXXXXXXX, XXXXXXXXXX
Case 1: Operation 1: 222B0CDD00 Operation 2: FFFFFFFF55 Operation 3: AABFCF4444 Operation 4: 0004030000 Operation 5: AABFCFFF55
______________________________________________________ 2171false
As a child, did you ever dream of playing in a maze? If you had thought about it, you may have come up with the idea of marking your paths as you went along. If you were trapped, you could then go back to the last crossing and take another path. By doing this, your actually applying what is called backtracking. This problem is about trying to get out of a maze.
Given a maze and a starting point within, you are to determine whether there is a way out. There is only one exit from the maze. You may move horizontally or vertically (but not diagonally) in any direction in which there is an open path, but you may not move in a direction that is blocked. If you move into a position where you are blocked on three sides, you must go back the way you came (backtrack) and try another path.
The should come from a text file. The file contains the original maze, represented as a square matrix of symbols, with one row of the matrix per line. Each symbol is a character that indicates whether the corresponding maze is an open path (`O'), a trap (`+'), or the exit (`E'). The size of the maze is 10x10 positions. At the end of the maze in the input file, there a series of starting position coordinates. Each line contains a pair of values, representing the row and the column of the starting position in the maze. Your task is to process each of these positions in your quest for the exit from the maze.
Processing
For each starting position, start your move into the maze from the given starting position (in terms of a row and a column numbers) until you either get to `E' (exit) or get trapped (cannot move). You can move only where `O' is found.
For each of the ten starting positions, print out the result of your move in the maze, by displaying either Exit or Trapped in front of the starting position.
O O + E + O O + + + 1 2 O + + O + O + O O O 10 1 O O O O O O + O + O 10 8 + + + + + O + + O O 7 6 O O O + O O O + O + 1 7 O + O + O + + + O + 8 7 O + O + O O O + O O 7 9 + + O + + + O + + O 9 3 O + O O O O O + + O 7 1 O + O + + O + O O O 2 8
Starting Position Result 1,2 Exit 10,1 Trapped 10,8 Trapped 7,6 Exit 1,7 Exit 8,7 Exit 7,9 Trapped 9,3 Exit 7,1 Exit 2,8 Trapped
______________________________________________________ 2172false
In this problem you will implement the MerkleHellman Knapsack cryptosystem. The encryption and decryption algorithms are based on solving a knapsack problem. The knapsack problem consists of finding a way to select some of the items to be packed such that their sum (the amount of space they take up) exactly equals the knapsack capacity (the target). Formally the knapsack problems is as follows: given a set S = {a_{1}, a_{2},...a_{n}} and a target sum T, where each a_{i} 0, is there a selection vector V = {v_{1}, v_{2},...v_{n}} each of whose elements is 0 or 1, such that (a_{i}*v_{i}) = T.
The idea behind MerkleHellman scheme is to encode a binary message as a solution to a knapsack problem reducing the ciphertext to the target sum obtained by adding terms corresponding to 1s in the plaintext. That is, blocks of plain text are converted to knapsack sums by adding into the sum the terms that match with 1bits in the plaintext as shown below:
Plaintext:  1  0  1  0  0  1  
Knapsack:  1  2  5  9  20  43  
Ciphertext:  49 
Plaintext:  0  1  1  0  1  0  
Knapsack:  1  2  5  9  20  43  
Ciphertext:  27 
The receiver will have to use the ciphertext (the target sum) to recover the plaintext.
A knapsack problem is said to be ``easy" if k a_{k} > a_{j}. The solution for the easy knapsack problem is straightforward, and can be achieved in O(n). Furthermore, there exists a way for transforming an easy knapsack set S into a noneasy knapsack H simply by multiplying the elements of S by w mod n where w and n are well chosen integers. Formally the terms of H are: h_{i} = (w*s_{i}) mod n
For example if S = {1, 2, 4, 9}, w = 15, and n = 17 then H = {15, 13, 9, 6}.
Encryption algorithm (executed by the sender)
H is called the public key and is made public by the receiver
Decryption algorithm (executed by the receiver)
The tuple (S, n, w) is called the private key and is kept secret by the receiver
The input consists of N test cases. The number of them (N) is given on the first line of the input file. Each test case begins with a line containing a plaintext to be encrypted. The second line contains the number of elements (m) in the knapsack S that show in the third line. The knapsack elements are positive integers separated by space. The fourth line of each text case contains n and w in this order separated by space.
Print exactly 3 lines for each test case. The first line should contain the encrypted values of the plaintext of the set separated by space. The second line should contain the plaintext obtained by applying the decryption algorithm to the plaintext, preceded by `Recovered plain text: '. The third line should contain the value of w^{1}
2 Salaam! 4 1 2 4 9 17 15 hello there? 4 1 2 4 9 19 7
29 25 22 16 22 28 22 16 22 16 22 44 9 16 0 24 Recovered plain text: Salaam! 8 23 7 23 20 23 21 23 21 23 36 9 0 29 14 23 7 23 20 29 9 23 20 15 36 0 16 Recovered plain text: hello there? 11
______________________________________________________ 2173false
An arithmetic progression is of the form a, a + b, a + 2b, ..., a + nb where n = 0, 1, 2, 3.... Assume a and b are nonnegative integers (0, 1, 2, 3,...).
Write a program that finds all arithmetic progressions of length n in the set S of bisquares. The set of bisquares is defined as the set of all integers of the form p^{2} + q^{2} (where p and q are nonnegative integers).
As input, your program should accept the length of progressions N to search for and an upper bound M to limit the search to the bisquares in the range from 0 to M. Each line of the input file contains N M. Assume M10, 000.
For each pair N, M in the input file, you should print line showing the pair N, M followed by all the progressions found. If no progressions are found, you program should write No progressions found.
8 200 13 100
8 200 Difference of 12: 1 13 25 37 49 61 73 85 13 25 37 49 61 73 85 97 25 37 49 61 73 85 97 109 37 49 61 73 85 97 109 121 Difference of 24: 1 25 49 73 97 121 145 169 2 26 50 74 98 122 146 170 25 49 73 97 121 145 169 193 26 50 74 98 122 146 170 194 13 100 No Progressions found
______________________________________________________ 2174false
Generating random numbers is ususally done through a function of the form:
The numbers generated will be between 0 and MOD  1. However this function will generate the same pattern of numbers in a cyclic manner. A carful choice of the STEP and MOD will minimize this problem by generating a Uniform distribution of all the values between 0 and MOD  1 inclusive.
For example, if STEP = 3 and MOD = 5, the function will generate the series of pseudorandom numbers 0, 3, 1, 4, 2 in a repeating cycle. So all the numbers between 0 and MOD  1 are generated including 0 and MOD  1 every MOD iterations of the function. Note that by the nature of the function to generate the same seed (x + 1) every time seed (x) occurs means that if a function will generate all the numbers between 0 and MOD  1, it will generate pseudorandom numbers uniformly with every MOD iterations.
If STEP = 15 and MOD = 20, the function generates the series 0, 15, 10, 5 (or any other repeating series if the initial seed is other than 0). This is a poor selection of STEP and MOD because no initial seed will generate all of the numbers from 0 and MOD  1.
Your task is to determine if the choices of STEP and MOD will generate a uniform distribution of pseudorandom numbers.
Each line of input will contain a pair of integers for STEP and MOD in that order (1STEP, MOD100000).
For each line of input, your program should print the STEP value rightjustified in columns 1 through 10, the MOD value rightjustified in columns 11 through 20 and either ``Good Choice" or ``Bad Choice" leftjustified starting in column 25. The ``Good Choice" message should be printed when the selection of STEP and MOD will generate all the numbers between and including 0 and MOD  1 when MOD numbers are generated. Otherwise, your program should print the message ``Bad Choice". After each output test set, your program should print exactly one blank line.
3 5 15 20 63923 99999
3 5 Good Choice 15 20 Bad Choice 63923 99999 Good Choice
______________________________________________________ 2175false
Let's consider a set, that will call Sigma, which consists of an integer sequence with the following properties:
Given an integer n as input. Your program should construct and outputs a sequence of integers, with minimal length, satisfying the properties above for n.
Note that there can be more than one sequence satisfying the properties above. Your program should output the one with the maximal sum.
The input consists of 100 test cases. Test cases are stored in an input file. Each test case in the file is stored in a separate line and the number `1' marks the end of the input file.
The output file should follow this organization: Each test case output consist of a sequence of integers separated by one blank.
3 4 9 77 80 87 99 1
1 2 3 1 2 4 1 2 4 8 9 1 2 4 6 9 17 34 68 77 1 2 4 8 16 32 64 80 1 2 4 8 16 24 28 29 58 87 1 2 4 8 16 32 33 66 99 ______________________________________________________ 2176falseA lattice point is a point (x, y) in the 2dimensional xyplane with x, y Z, where Z be the set of integers. Let
P(r) = {(x, y) x^{2} + y^{2}r^{2},(x, y) is a lattice point in the xyplane}and we denote D(r) be the number of elements in P(r). For each lattice point (x, y) in the xyplane, letS(x, y) = {(u, v) xux + 1, yvy + 1}andB(r) = {(x, y) x^{2} + y^{2}r^{2}, x and y are real numbers}Then it is easy to verify that when r >
B(r  ) S(x, y) B(r + )We know that
Area(S(x, y)) = Area(S(x, y)) = 1 = D(r).Hence
(r  )^{2} < D(r) < (r + )^{2}This implies
(1  )^{2} < < (1 + )^{2}It yields
=So if we can calculate D(r) for a large r, then we can estimate the value of .
The following C function can be used to calculate the value of D(r) withing a reasonable aumount of time when r is a small integer, say e.g., 1r10, 000.
long D(long r) { long x,y,count=0; for(x=r;x<=r;x++) for(y=r;y<=r;y++) if(x*x+y*y<=r*r) count++; return count; }
Is is easy to obtained D(1) = 5, D(2) = 13, D(3) = 29, and D(10000) = 314159053 using this program. Recall that = 3.14159.... Your task is to find D(r) for a large r within a reasonable aumount of time.Input
There are five lanes in the input file, the kth line contain an integer n_{k}(1n_{k}100, 000, 000).
Output
List integer n_{k} in line 2k  1 and the value of D(n_{k}) in line 2k for k = 1, 2, 3, 4, 5.
Sample Input
1 2 3 10000 100000000Sample Output
1 5 2 13 3 29 10000 314159053 100000000 31415926535867961______________________________________________________ 2177false
Let a_{1}, a_{2},..., a_{n} be n relatively prime positive integers. A positive integer k has a representation by a_{1}, a_{2},..., a_{n} if there exist nonnegative integers x_{1}, x_{2},..., x_{n} such that k = x_{1}a_{1} + x_{2}a_{2} + ^{... }+ x_{n}a_{n}. The linear Diophantine problem of Frobenius is to determine the largest integer g(a_{1}, a_{2},..., a_{n}) with no such representation.
The linear Diophantine problem of Frobenius has very practical application. It is equivalent to the problem of coin exchange. Given sufficient supply of coins of denominations a_{1}, a_{2},..., a_{n}, determine the largest amount which cannot be formed by means of these coins.
Mathematical problems, such as this, are usually difficult to solve. We shall consider a simple case in which n = 2. In addition to g(a_{1}, a_{2}), we shall also want to find n(a_{1}, a_{2}) the number of positive integers that cannot be represented by a_{1} and a_{2}.
Write a program to compute g(a_{1}, a_{2}) and n(a_{1}, a_{2}). The following theorem may help you in designing your program.
Theorem: A positive number k = qa_{1} + r, 0 < r < a_{1}, can be represented by a_{1}, a_{2},..., a_{n} if and only if kt_{r}, where t_{r} is the smallest positive integer which has the same residue r modulo a_{1} and can be represented by a_{2}, a_{3},..., a_{n}.Input
The input file will consist of one or more cases. Each case contains two positive integers a_{1} and a_{2} in a line. The product of a_{1} and a_{2} is less than 2^{32}. A line containing two zeros follows the last case, and terminates the input file.
Output
For each case a_{1} and a_{2} in the input file, the output file should contain a line with two numbers g(a_{1}, a_{2}) and n(a_{1}, a_{2}) separated by a blank.
Sample Input
3 5 23 20 0 0Sample Output
7 4 417 209______________________________________________________ 2178false
A sawtoothed chessboard is a chessboard whose boundary forms two staircases from left down to right. See the following figure for an example.
A square is dominated by a rook if it is in the same row or column with this rook. Your task is to determine the minimun number of rooks such that every square in a sawtoothed chessboard is dominated by at least one rook. For example, see the above figure again. It needs only four rooks located at the squares with a dot to dominate all the squares.
Input
The input data will contain multiple test cases. Each test case will consist of less than 100 pairs of integers which represent the row and column indexes of the corner points, in clockwise order, in a sawtoothed chessboard starting from the upperleft most corner. For example, the corner points in the above figure are v_{1}, v_{2},..., v_{12}, respectively. Each corner point is represented by its x and y coordinates in the 2dimensional xyplane whose values are in the range from 1 to 100. For example, the indexes of v_{1},v_{2} and v_{3} are (1,1), (1,4) and (3,4), respectively. The input for each test case will be terminated with a pair of zeros, wich are not to be treated as the indexes of a corner point. An additional pair of zeros will follow the last test case.
Output
For each test case, determine the minimun number of rooks needed to dominate all of the squares in the sawtoothed chessboard described in the test case. Display, one test case a line, the test case number (they are numbered sequentially starting with 1) and the number of rooks which are separated by one blank.
Sample Input
1 1 1 4 3 4 3 6 4 6 4 7 8 7 8 6 6 6 6 3 4 3 4 1 0 0 1 1 1 3 3 3 3 6 5 6 5 2 3 2 3 1 0 0 0 0Sample Output
1 4 2 3______________________________________________________ 2179false
In the year 2199, the earth is united into a Federation with the head of the Federation being the Prime Minister. The newly elected Prime Minister Q decided to colonize Mars by constructing cities and interconnection pathways between cities. Acording to the geographical survey, the Federation has chosen a square piece of flat land to construct N, 2N10, 000, cities. Each city h is given a coordinate (x_{h}, y_{h}) at the 2dimensional xyplane with the point of origin at the southwest corner of the piece of the land. Each city is in the shape of a circle with a radius of exactly 0.5 kilometer. The coordinate is the center of the city. It is known that the values of x and y coordinates of any city are in units of 1 kilometer and are positive integers smaller or equal to 100,000. No two cities have the same coordinates. Since Mars has unpredictable weathers, Prime Minister Q decided to build covered pathways between the cities. In order to speedup the construction, simplify the construction plan and save budget, only northsouth or eastwest bounded pathways connecting exactly two cities are constructed. The height and width of each pathway is exactly 3 meters. In addition, no two pathways intersect except at the N cities. According to the above, Minister of Transportation T designs the following pathway constructing plan:
The construction plan is approved by Primary minister Q. Your task is to help Minister of Transportation T finding the total distance (in kilometers) of the pathways constructed.
For example, there are 9 cities in the following piece of flat land whose coordinates are (1,1), (3,1), (6,1), (7,2), (1,3), (5,3), (7,3), (3,5) and (6,5), respectively. There are 6 pathways constructed with a total distance of 10 kilometers.
The input file contains multiple test cases. In each test case, a list of coordinates for the cities are listed one city per line with 2 positive numbers indicating their x and y coordinates. A line with two 0's separates two test cases. The end of the file is a line with two 1's.
For each test case, output the total number of pathways constructed and their total distance in kilometers in one line separated by one blank.
1 1 3 1 6 1 7 2 1 3 5 3 7 3 3 5 6 5 0 0 1 1 4 1 0 0 1 1
6 10 1 2
______________________________________________________ 2180false
In a country, there are N persons, labeled by 1, 2,..., N. The country has exactly two plitical parties. All of the people in this country belong to at most one of the two political parties. If two persons join the same party, then they are friends to each other and are enemies if they belong to different parties. Assume that N is known in advance. Let p_{1}, p_{2},..., p_{w},... be a sequence of operations where each operation p_{w} is one of the following two types: (1) a pair of persons indicating that these two persons are enemies, or (2) a query asking the set confirmed friends and enemies for a person using the information aviable in the prefix of sequence p_{1}, p_{2},..., p_{w1}. Your task when N and the sequence is given, is to answer the queries mixed in the sequence one by one in sequence. We use a pair of positive integers (i, j), 1i, jN, to represent a type (1) operation and use the pair (0, k), 1kN, to represent a type (2) operation. For example, when N = 5 in the following input sequence:
p1 1 3 p2 5 2 p3 2 4 p4 0 2 p5 1 4 p6 0 4 . . . .
At p_{4} it should show that there are no confirmed friend for person 2 and two confirmed enemies (4 and 5) for person 2 according to all inputs appeared before p_{4}. At p_{6} it should show that there are two confirmed friends (3 and 5) and two enemies (1 and 2) for person 4.
Given the input sequence, let p_{w} = (i, j) be a type (1) operation. Then p_{w} conflicts with the previous operations, if it is already confirmed that i and j are friends to each other according to the prefix p_{1}, p_{2},..., p_{w1}. To handle this situation, we should completely ignore this conflict relation and assume that it does not exist. For example, in the following input sequence when N = 5, the operations p_{4} = (4, 5) and p_{7} = (1, 2) should be ignored and p_{5} and p_{8} will have the same outputs for the queries p_{4} and p_{6} in the previous input sequence:
p1 1 3 p2 5 2 p3 2 4 p4 4 5 p5 0 2 p6 1 4 p7 1 2 p8 0 4 . . . .
The input file contains several test cases eaxch of which separated by a pair of 0's. For each test case, the first line contains the number of persons N, 1N30, 000. Then in each of the following input lines, it includes two integers i and j separated by blanks where 0iN and 1jN to denote an operation. The number of operations for each test case is within 1,100,000. If i is equal to 0 then a query for person j's current status should be printed out. Otherwise i and j are a pair of enemies. Note the enemy relation between i and j is ignored if a conflict condition occurred. A line consists of a single `0' indicates the end of the file.
For each query of the person k, you should print out one line to list out number of friends and number of enemies for person k known at the current stage as follows:
person k's status: number of friends, number of enemies
Print a blank line after each output of a query. Print a line with ten ='s at the end of each test case.
5 1 3 5 2 2 4 0 2 1 4 0 4 0 0 5 1 3 5 2 2 4 4 5 0 2 1 4 1 2 0 4 0 0 0
person 2's status: 0, 2 person 4's status: 2, 2 ========== person 2's status: 0, 2 person 4's status: 2, 2 ==========
______________________________________________________ 2181false
Here we introduce a special version of the combinatoric game called Nim. This progressively finite takeaway game involves 4 piles of stones on a table. In this game, the two players take turns removing at least one but at most 3 stones from exactly one of the piles. The playes who takes the last stone of the table losses.
The configuration of an instance of this Nim game can be described with four nonnegative integers representing the sizes of these four piles. i.e., (p_{1}, p_{2}, p_{3}, p_{4}), where the kth, 1k4, number p_{k} representing the current size of the kth pile.
A configuration of this Nim game is winnable if a player facing this configuration can allway find a way to win the game. To write a program that plays the Nim game perfectly, we need to decide whether a given instance of the Nim game is winnable to the current player or not facing the given configuration. For example, the configuration (0,0,0,2) is winnable by removing one stone from the last pile; however, you can verify that neither (0,0,0,5) nor (2,2,0,0) is winnable. Further, to make the problem easier the number of stones on each pile is at most 9.
The first line contains n, the number of Nim game configurations, which can be as large as 20. After n, there will be n lists of Nim game configurations; each line contains four integers p_{1},p_{2},p_{3} and p_{4}. Note that 0p_{1}, p_{2}, p_{3}, p_{4}9.
For each configuration appeared in the input, decide whether it is winnable or not. Output a single number `1' if the instance is winnable; otherwise, output `0'.
4 0 0 0 5 0 0 0 6 0 0 2 2 1 2 3 4
0 1 0 0
______________________________________________________ 2182false
There are N, 1N1, 000, rectangles in the 2D xyplane, each rectangle is associated with exactly one of the three colors: RED, BLUE or GREEN. The four sides of a rectangle are horizontal or vertical line segments. Rectangles are defined by their lowerleft and upperright corner points. Each corner point is a pair of two nonnegative integers in the range of 0 through 50,000 indicating its x and y coordinates. We say that the intersection area of rectangles is tricolored if there are at least one RED, one BLUE and one GREEN rectangles covering this intersection area of these rectangles.
Example: Consider the following three rectangles and their colors: rectangle 1: < (0, 0) (4, 4) RED >, rectangle 2: < (1, 1) (5, 2) BLUE >, rectangle 3: < (1, 1) (2, 5) GREEN >. The tricolored intersection rectangle is at (1,1) (2,2) with an area of 1.
The input consist of multiple test cases. A line of 5 1's separates each test case. An extra line of 5 1's marks the end of the input. In each test case, the rectangles are given one by one in a line. In each line for a rectangle, 5 nonnegative integers are given. The first two are the x and y coordinates of the lowerleft corner. The next two are the x and y coordinates of the lowerleft corner. The last integer indicates the color of the rectangle with 1 means RED, 2 means BLUE and 3 means GREEN.
For each test case, output the total tricolored intersection area in a line.
0 0 4 4 1 1 1 5 2 2 1 1 2 5 3 1 1 1 1 1 0 0 2 2 1 1 1 3 3 2 2 2 4 4 3 1 1 1 1 1 1 1 1 1 1
1 0
______________________________________________________ 2183false
A deadlock is defined as a set of processes entering a state where each process is waiting for response (or computing resources) from other processes. For example, in OS text books, there are deadlock detection algorithms to detect if a set of processes is deadlocked during runtime.
The deadlock detction problem here is to prevent deadlocks from happening before a program is executed (or even before the program is implemented). The problem is to find if there are potential deadlocks among a set of processes without executing the program.
Assume that processes communicate via send and receive with buffer of zero lenght; that is, when a process invokes send, it must block (or wait) until the message is received by the designated process via receive. When a process invokes a receive command and there is no message available, the process must block (or wait) until a message arrives. Note that it is possible for two processes to send to the same process P and then P receive the two in sequence. For example, there are three processes P1,P2, and P3 as follows:
P1: P2: P3: do { do { do { msg1 = 1; msg2 = 2; receive(&msg); send(P3,msg1); send(P3, msg2); if (msg == 1) ..... ..... send(P1,''ACK''); receive(&msg); receive(&msg); else } while (1); } while (1); send(P2,''ACK''); } while(1);
A sender invoking a send command must specify the receiving process. When P1 invokes send, it will wait until the message is retrieved by P3. The receive command, on the other hand, does not need to specify the process from wich the message is sent, so there is no process ID in the receive command. The synchronization among the processes constitutes a synchronization structure. If there is no deadlock in a system, we say the system is wellsynchronized.
Researchers discovered that we can abstract every process is abstracted into a finitestate machine which is expressed using a directed graph with labels on the vertices and edges. The following game on the abstracted graphs can be used to solve a simplified version of the deadlock detection problem. You are given n, 1n6, directed graphs G_{1}, G_{2},..., G_{n} abstracted from processes. Let V_{i} and E_{i} be the vertices and edges of G_{i}, respectively. You may assume each graph has less than 20 nodes. The nodes of V_{i} are numbered 0, 1,..., V_{i}  1. Each edge e_{i, j} E_{i} is denoted as s_{i, j} t_{i, j} indicatin and edge from the node s_{i, j} to the node t_{i, j}. Each edge is labeled with an integer label (e_{i, j}) that can be either positive or negative, but not 0. Initially, the game starts by picking a node s_{i} in each graph G_{i} and then place a stone in it. In each of following steps, we move exactly two stones s_{i} and s_{j} using the following rules:
Hence we can describe each step of the game using an ntuple vector S_{i} = < c_{i, 1}, c_{i, 2},..., c_{i, n} >, where c_{i, j} is a node in the graph G_{j}. The game ends when it is not possible to make any more moves. The steps that cannot be further advanced are called deadlocked steps.
An example is given below for a set of games without deadlocked steps and a set of games with a deadlocked step. In Figure 1, there are three graphs.In each graph, we initially put a stone in the nodes as shown in the figure. Following the rules described above, for example, we camn move the stones of G1 and G3 to their next nodes by following the edges labeled with `111' and `111', respectively. Continuously, you can allways find two stones to move without any deadlock. We can verify that this example has no deadlocks states. Figure 2(a) is an example that has deadlocks. Suppose we initially put the stones as shown in Figure 2(a). Suppose we move the stone of G1 and G3 to become a state in (b). In (b), we can not make any further movements, thus is deadlocked. It can be veritied that the number of all possible deadlock steps in this example is 1.
Given n, the set of graphs and their starting nodes, yopur task is to find the number of all the possible deadlocked steps from the starting step.
The input contains multiple yest cases. The first line contains the number of graphs n and the followed by the data of the n graphs. Each graph starts with three integers s t i, where s is the number of nodes, t is the number of transactions, and i is the starting node. Following the line of the three integers s, t and i is t lines of directed edges in the form of a b c, wich represents and edge with label b from node a to node c. A line with three 0`s means the end of a test case. When the number of graphs is 0 (n = 0), it is the end of all test cases.
For each test case, output the total number of deadlock steps in a line.
3 2 2 0 0 111 1 1 333 0 2 2 0 0 222 1 1 444 0 3 4 0 0 111 1 0 222 2 1 333 0 2 444 0 0 0 0 3 2 2 0 0 747 1 1 777 0 2 2 0 0 747 1 1 911 0 2 2 0 0 747 1 1 911 0 0 0 0 0
0 1 ______________________________________________________ 2184falseThere are several ancient Greek texts that contain descriptions of the fabled island Atlantis. Some of these texts even include maps of parts of the island. But unfortunately, these maps describe different regions of Atlantis. Your friend Bill has to know the total area for which maps exist. You (unwisely) volunteered to write a program that calculates this quantity.
Input
The input file consists of several test cases. Each test case starts with a line containing a single integer n (1≤n≤100) of available maps. The n following lines describe one map each. Each of these lines contains four numbers x1 ; y1 ; x2 ; y2 (0≤x1<x2≤100000; 0≤y1<y2≤100000), not necessarily integers. The values (x1 ; y1) and (x2 ; y2) are the coordinates of the topleft resp. bottomright corner of the mapped area. The input file is terminated by a line containing a single 0. Dont process it.Output
For each test case, your program should output one section. The first line of each section must be "Test case #k", where k is the number of the test case (starting with 1). The second one must be "Total explored area: a", where a is the total explored area (i.e. the area of the union of all rectangles in this test case), printed exact to two digits to the right of the decimal point. Output a blank line after each test case.Sample Input
2 10 10 20 20 15 15 25 25.5 0Sample Output
Test case #1 Total explored area: 180.00______________________________________________________ 2185falseYour little sister got a new mechanical building kit, which includes many cogwheels of different sizes. She started building gears with different ratios, but soon she noticed that there were some ratios which were quite difficult to realize, and some others she couldnt realize at all. Since the most intelligent being in your family is your computer (as you have always been claiming), now it has to figure out which ratios are achievable.
There you are! Thats the punishment for bragging about your computer. Now, you must write a program that will do the job: your sister tells you the sizes of the cogwheels (the numbers of cogs they have) in her kit. Then, she tells you the ratios of the gears she would like to build. Your computer has to decide whether this is possible and, if so, determine how to connect the wheels to obtain the ratio.
Here is an example: lets assume there are cogwheels with 6, 12, and 30 cogs. Your sister wants to realize a gear of ratio 4 : 5. One possible solution is the following:
Input
The input file contains the descriptions of several sets of cogwheels, each one followed by a list of ratios to be realized.
A set of cogwheels is described by one line starting with the number n of sizes of cogwheels (1 ≤ n ≤ 20). The rest of the line will consist of n numbers a_{1},...,a_{n}, the numbers of cogs on the wheels. There will always be at least 5 and at most 100 cogs per wheel. You may assume that your sister has an infinite supply of wheels of each size.
In your sisters building kit (and thus, in the input file), the number of cogs on every wheel is divisible by the number of cogs on the smallest wheel in the kit.
The line describing the set of cogwheels is followed by a list of ratios to be realized. Each ratio to be realized is given by one line containing two numbers a_{j} and b_{j} (1 ≤ aj , bj ≤ 10000; a_{j} != b_{j} ), meaning a_{j} : b_{j} . The line 0 0 marks the end of that list.
At the end of the input file, there will be a line containing only a zero (instead of the number of cogwheels of the next set).
Output
Output one section for each set of cogwheels. The sections should start with the line Set #k where k is the number of the set.
Then, output the results for the ratios from the test set. Output exactly one line for each ratio. Each of these lines should start with Ratio a_{j} :b_{j} :, followed either by Impossible if the ratio cannot be realized with the given set of cogwheels, or a description of a gear which realizes the ratio. This description has to be in the notation described above: a blankseparated list of transitions, each transition having the form c_{i}:d_{i}.
The gear does not need to be the smallest possible; we guarantee that if there is a solution then there is a solution using at most 10000 transitions. Any solution with at most that many transitions is an acceptable answer.
Every section should be followed by a blank line.
Sample Input
3 6 12 30 4 5 1 6 0 0 0Sample Output
Set #1 Ratio 4:5: 12:30 12:6 Ratio 1:6: Impossible______________________________________________________ 2186falseThe new boss of a rural fire service of the ``rectangular state", whose map is drawn on a grid, with integer coordinates that are multiples of a meter, (0 0) for the lower left corner and (10000 10000) for the upper right corner, in a nation far away used to be an IT person. She believes that a good computer system, especially one based on provably correct algorithms, can outperform humans in stressful situations. That is the reason, when asked; she could not pass the opportunity of posing this problem to the best problemsolvers in the southern hemisphere.
75 70 65 60 55 50 F F 45 40 35 30 25 H 20 15 10 5 0 H F H F 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90
It is easy to describe, the boss said: At the height of the fire season, the department maintains a database of fire fighter unit locations and the reported sightings of fire. The horizontal and vertical distance, of the closest grid point, from the left lower corner of the state is used to describe the location of a fire or a fire fighter unit. An experienced team of officers dispatches each of the units to one of the fires, with the objective that the longest time for a unit to reach a fire is minimized. At the end of a long day, members of the team are exhausted and their judgement may not be the best possible. The above example shows 4 fires (marked by the letter F) and 3 units (marked by the letter H) already deployed in the field.Your task is to program a method for dispatching the fire fighter units to fire locations so that they arrive at their destinations in the shortest possible time.
Input
Input to this problem consists of a sequence of one or more scenarios. Several lines describe each scenario as follows:
The input will be terminated by a line that consists of three zeros (0 0 0). This line should not be processed.
For each scenario, the output is a single line that contains the shortest time, roundedup if necessary (e.g., all values larger than ``3" and less than ``4" are roundedup to ``4"), in seconds for the H fire fighters to arrive at H different fire locations.
3 4 10 0 0 25 25 50 0 0 50 50 50 25 0 75 0 0 0 0
4
______________________________________________________ 2187false
Rob runs a oneman security firm. When he is not out on the street doing what PIs usually do, he makes his money watching videos on his broadband connected computer (Security video streams, that is). Being a very stressful job, even with its meager pay of no more than 200 dollars for a video stream, as he is required to raise the alarm immediately when a potential security breach occurs, he elected to impose the rule of not watching more than two video streams at any time. For each job Rob knows the starting time (given in minutes with ``0" as midnight and all times belong to the same day), duration (in minutes) and payment (in dollars).
Your task is to write a program to help Rob to select the videos he must watch to maximize his pay for a given day.
Input to this problem consists of a sequence of one or more scenarios. Three lines describe the situation of each scenario as follows:
The input will be terminated by a line that consists of two zeros (0 0), separated by a single space. This line should not be processed.
For each scenario, the output is a single line that contains Rob's maximum possible pay for the day.
1 6 20 500 120 10 600 100 100 640 30 50 700 200 90 1100 1200 200 650 1000 0 0
460
______________________________________________________ 2188false
A local guru has written a script for extracting necessary information from the PC^{}2 databases in the following format:
Our guru also scrambled the extracted information, by permuting the ``Team number" entries, and provided the permutation number as the clue for the organizer. He claims this is a good method to maintain privacy when number of submissions is small. For example, for the contest with four submissions, shown on the left side below, the ``Team number" entries have been permuted according to the 9th permutation of four items and shown on the right side.
3 2 765629 0  17 2 765629 0 
17 4 1120132 0  3 4 1120132 0 
3 2 1895629 3  3 2 1895629 3 
6 3 9024555 0  6 3 9024555 0 
You may recall that the number of permutations of ``x" items is ``x!". The table below shows the permutations of four (4) items sorted in lexicographically increasing order, as an example, along with their permutation numbers from 1 to 24.
1  1  1  1  1  1  2  2  2  2  2  2  3  3  3  3  3  3  4  4  4  4  4  4 
2  2  3  3  4  4  1  1  3  3  4  4  1  1  2  2  4  4  1  1  2  2  3  3 
3  4  2  4  2  3  3  4  1  4  1  3  2  4  1  4  1  2  2  3  1  3  1  2 
4  3  4  2  3  2  4  3  4  1  3  1  4  2  4  1  2  1  3  2  3  1  2  1 
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24 
Your task is to write a program to use the data provided by our guru, descramble the `` Team number" entries, and to declare the winner, or winners.
Input to this problem consists of a sequence of one or more contests. Each contest is described by several lines as follows:
The input will be terminated by a line that consists of three zeros (0 0 0), separated by a single space. This line should not be processed.
For each contest, the output is one line that contains the contest label and numbers of the winning team numbers (sorted in increasing order) as shown in the Sample Output below.
1 5 6 6 3 3 10 30 100 6 1 3602455567 0 3 2 6589562919 4 3 2 9076562919 0 6 4 1120132409 0 3 2 7189562919 3 17 3 9902455567 0 2 5 6 120 3 10 10 30 100 6 1 3602455567 0 6 2 6589562919 5 5 2 9076562919 0 17 4 1120132409 0 3 4 7189562919 0 3 3 9902455567 0 0 0 0
Contest 1 Winner: Team 17 Contest 2 Winner: Team 5 and Team 17______________________________________________________ 2189false
A  Mobile Casanova Input: Standard Input Output: Standard Output 
Mobile Phone industry is the fastest growing industry in Wonderland. The three prominent mobile service providers of Wonderland are Coktel, Anglolink and Grinding Phone. All three operators provide very cheap rate packages after 12:00 AM. The name of their packages are The Thief Talk (Chorer Alap in Bangla), Insomnia and The Vampire Chat respectively. These cheap packages have inspired many people to disturb others at Night.
Case 1:
017113223968
Case 2:
01187239192
01711322396400
01711389821
Problem setter: Shahriar Manzoor, Special Thanks: Syed Monowar Hossain
______________________________________________________ 2190falseProfessor AlwaysLate is notorious for having something to say past the end of class time, and even past the start time of following classes. This habit is not viewed kindly by the students' rights movement, which motivated them to collect data about such conduct. The students' rights movement wants to process their extensive data collection and extract some useful information for their annual report, and you are asked to help. Your task is to write a program to read a number of lines, where each line contains a record about a single class, and calculate the average length of time spent past the end of class for Professor AlwaysLate.
The input consists of a series of scenarios. In each scenario, the input starts with a positive integer N
For each scenario, the output of your program is a single integer that represents the average number of minutes that Professor AlwaysLate spends lecturing past the end of his official class finish time rounded down (that is, truncated) to the nearest minute.
It is worth mentioning that the students's rights movement considers early finishing of a class as a class finished on time, as demonstrated in the second example below.
4 10 50 10 55 12 50 13 0 17 50 17 50 13 45 14 0 4 10 50 10 55 12 50 13 0 17 50 17 40 13 45 14 0
7 7
______________________________________________________ 2191false
B  Potentiometers Input: Standard Input Output: Standard Output 
A potentiometer, or potmeter for short, is an electronic device with a variable electric resistance. It has two terminals and some kind of control mechanism (often a dial, a wheel or a slide) with which the resistance between the terminals can be adjusted from zero (no resistance) to some maximum value. Resistance is measured in Ohms, and when two or more resistors are connected in series (one after the other, in a row), the total resistance of the array is the sum of the resistances of the individual resistors.
In this problem we will consider an array of N potmeters, numbered 1 to N from left to right. The left terminal of some potmeter numbered x is connected to the right terminal of potmeter x1, and its right terminal to the left terminal of potmeter x+1. The left terminal of potmeter 1 and the right terminal of potmeter N are not connected.
Initially all the potmeters are set to some value between 0 and 1000 Ohms. Then we can do two things:
The input consists less than 3 cases. Each case starts with N, the number of potmeters in the array, on a line by itself. N can be as large as 200000. Each of next N lines contains one numbers between 0 and 1000, the initial resistances of the potmeters in the order 1 to N. Then follow a number of actions, each on a line by itself. The number of actions can be as many as 200000. There are three types of action:
A case with N=0 signals the end of the input and it should not be processed.
For each case in the input produce a line "Case n:", where n is the case number, starting from 1.
For each measurement in the input, output a line containing one number: the measured resistance in Ohms. The actions should be applied to the array of potmeters in the order given in the input.
Print a blank line between cases.
Warning: Input Data is pretty big (~ 8 MB) so use faster IO.
3 100 100 100 M 1 1 M 1 3 S 2 200 M 1 2 S 3 0 M 2 3 END 10 1 2 3 4 5 6 7 8 9 10 M 1 10 END 0  Case 1: 100 300 300 200
Case 2: 55 
Problem setter: Joachim Wulff, Special Thanks: Shahriar Manzoor
______________________________________________________ 2192falseC  Collecting Marbles Input: Standard Input Output: Standard Output 
2 3 4 3 1 2 3 4 5 6 7 8 9 10 11 12 1 1 3 4 1 1 2 2 1 1 3 3 3 3 3 2 1 3 4 6 1 11 2 3 1 1 3 3 1 1 2 3 2 1 3 3
 Test Case 1: 1 118 2 9 3 66
Test Case 2: 1 45 2 16 3 27

Problem setter: Abdullah al Mahmud, Special Thanks: Shahriar Manzoor
______________________________________________________ 2193falseD  Expression Input: Standard Input Output: Standard Output 
Professor Conrad loves to work with expressions and we all know that there are many well known techniques to evaluate expressions. After teaching his class about evaluating expression he gives his class a bit tricky assignment. As usual being the most brilliant programmer of the class, your classmates have grasped you to do the assignment for them. The assignment is stated below:
You are given an expression consisting only brackets, blank spaces and +/ operators and also some digits. You have to place the given digits in the blank spaces in such a way so that the value of the expression is maximum.
First line of the input file contains an integer N (N<=505) which denotes how many sets of inputs will be there. The description of each set is given below.
First line of each set contains a correct expression and the second line contains a sequence of digits. You can put any of this one of these digits in the blank spaces of the expression. In the input the blank spaces are denoted with # characters. You can assume that (a) The number of # signs in the expression and the number of given digits will be equal (b) There will be maximum eight consecutive # signs in the given expression (c) The length of the expression will be less than 200
For each set of input produce three lines of output. First line contains the serial of output, the second line contains the expression which produces maximum value and the third line contains this maximum value. If more than one expression produces maximum value then output the lexicographically smallest one. You can assume that (a) the maximum value of the expression will fit in a 32bit signed integer (b) Numbers in the expression can have leading zeroes.
3 ##(##+###) 3333333 #+# 31 ## 31  Case 1: 33(33+333) 333 Case 2: 1+3 4 Case 3: 31 2 
Problem setter: Shahriar Manzoor, Special Thanks: Derek Kisman
______________________________________________________ 2194falseE  The Luncheon Input: Standard Input Output: Standard Output 
Karim and Rahim go to the same restaurant once every day to have lunch. They both have their own list of favorite dishes but they dont necessarily eat their favorite dishes at lunch. The restaurant they visit have N dishes in total. Karim and Rahim choose a dish randomly (They both eat the same dish) from the N dishes and have it for lunch. They go to that restaurant regularly for D days. You have to find the probability that the number of days for which the dish chosen is a favorite of Rahim's is exactly twice the number of days for which the dish chosen is a favorite of Karim's.
The input file contains at most 600 sets of inputs. The description of each set is given below:
Each set starts with an integer N (0<N<37) which denotes the total number of dishes. Dishes are identified by integers from 1..N. Next line starts with an integer S (0≤S<N) which denotes the total number of Karims favorite dishes. Next S distinct integers are favorite dishes of Karim. All these integers are within the range (1..N). The Next line starts with an integer T (0≤T<N) which denotes the total number of Rahims favorite dishes. Next T distinct integers are favorite dishes of Rahim. All these integers are also within the range (1..N). The next line contains an integer D (0<D<101) which indicates how many days Karim and Rahim goes to the restaurant.
Input is terminated by a line containing a single zero.
For each set of input produce one line of output. This line contains the serial of output followed by the desired probability rounded to five digits after the decimal point. Look at the output for sample input for details. There is no special judge for this problem. But the judge data is such that errors less than _{Case 1: 0.07082}
Case 2: 0.02592
Case 3: 0.01501
Problem setter: Shahriar Manzoor, Special Thanks: Derek Kisman
______________________________________________________ 2195falseF  Counting Zeroes Input: Standard Input Output: Standard Output 
In our daily life we often meet some stupid persons. They tend to do things by hand which can only be done with computers. Our friend Hashmat is such a person and now he is counting with abacus, pencil and paper the summation of trailing zeroes of a particular number in all possible number systems (Of course, I am talking about the common number system like decimal, binary, hexadecimal or nbased number system).
The input file contains at most 400 lines of inputs. Each line contains a decimal integer n (0<n<=10^{13}).
Input is terminated by a line containing a single zero.