Sunteți pe pagina 1din 90

1.

The beginning of a record is identified by the begin-record-line that contains in addition to the `@' character and the record number, a number n denoting the number of options for recovering the record. A blank character precedes the number n. In case a record cannot be recovered due to any contradiction between the information contained in the record and the information provided by the company, the option number n is set equal to zero. The beginrecord-line is followed by n options for recovering the record. Each option begins with a begin-option-line that contains a number of slash character (/) pertinent to the option number, e.g., the second option will begin with a line containing two slashes (//). Each option for recovering a record contains fields in the normal order. The file ends with the end-file-line that contains in addition to the character `$' and the total number of records in the file, a number m denoting the total number of records recovered. A blank character precedes the number m. The output file structure is illustrated in sample output. Sample Input @1 gamma 436502; Beta Alpha; Nu5 321902; Epsilon, Theta; eta 123206; Sigma Kappa, Lambda; Zeta Delta; @2 Alpha, Beta; eta 123206; Sigma Kappa, Lambda; Nu5 321902; gamma 436-502; Epsilon, Theta; $2 Sample Output @1 0 @2 2 / gamma 436-502; Beta Alpha; Sigma Kappa, Lambda; Nu5 321902; eta 123206; Epsilon, Theta; // gamma 436-502; Theta Epsilon; Sigma Kappa, Lambda; Nu5 321902;

eta 123206; Alpha, Beta; $2

2. Normally for a given problem you are asked to find the solution. Here you are required to write a program to find the problem for which the solution is given. Let f = m/n be a proper fraction and F = {f1, f2,..., fk} be a set of k distinct unit fractions fi = 1/ni , i = 1, 2,..., k , where ni (not equal to 1 or n ) is a factor of n and k is a suitable integer. Recall that a proper fraction f is a number of the form / , where the numerator and the denominator are positive integers and 1 < . A unit fraction is a proper fraction with = 1 and > 1 . Since the numerator of each element of F is 1, the set F may be identified also by the set D = n1, n2,..., nk of denominators appearing in the elements of F. Consider the problem: given the set F , find the sum of elements of F and its solution: the sum f , where k is a nonnegative integer as large as possible. Given a solution f you are required to write a program to find F or equivalently find D . It should be noted that for a given solution there may exist no problem, exactly one problem or more than one distinct problem. Let p be the total number of distinct problems for a given solution. For example if f = then p = 2 , F = { , , } or { , , } and D = {3, 8, 12} or {4, 6, 8} . Again if f = then p = 0 since no F or D exists for the given f . Input The input may contain multiple test cases. For each test case there are two input lines. The first line contains the case number c and the second line gives the numerator m and the denominator n . The input terminates with an input `0' for c . The input is illustrated in sample input. Output For each test case print c , k and p in one line, where c is the test case number, k is the largest possible number of distinct unit fractions in F and p is the total number of distinct problems. In each of the next p lines, print a problem represented by k elements of D. The elements of D are printed in increasing order of magnitude. The problems are to be arranged in lexicographic order of the elements of D. Print a blank line between two successive test cases. Sample Input 1 13 18 2 13 24 0 Sample Output

100 232 3 8 12 468

3. The ABC class of 2003 consists of all outgoing students of ABC Institute of Information Technology of the year 2003. The class is engaged in developing a web site that aims to provide free services of various kinds. Considering the fact that people often lose contact with their old classmates and are eager to establish the lost contact after long years of separation a link has been kept in the web site for users to register and provide information about last school/college/university they attended and classmates they remember. Information gathered from users is included in a database that is used to process personalized queries related to information about classmates. In order to attract users, the site aims to display, while responding to personalized queries, some statistical information related to the database. In particular it is of interest for the users to know the largest number of classmates that exists in the database, who studied together in the same institution/institutions, viz., a) The same school (S), b) The same college (C), c) The same university (U), d) The same school and the same college (SC), e) The same school and the same university (SU), f) The same college and the same university (CU) and g) The same school, the same college and the same university (SCU). 4. The ABC class of 2003 seeks your help in writing a program to compute the seven statistics stated above. Assume that all registered users and classmates for whom information is given by a user are recorded in the database by name and associated school, college, university and years. However each one of them is also identified uniquely by an integer assigned arbitrarily. The integer representation is used in input/output. It should be noted that when a user A is listed as a classmate by another user B the user A may or may not list B as classmate. Further if A and B are classmates at a given level (school/college/university) then all classmates of A (or B) are classmates of B (or A) and A, B and their classmates attended the same institution at that level. Input The input may contain multiple test cases. For each test case the first line contains two integers K and N . The integer K is the case number and N( <5000) is the total number of users who have registered at the site and provided information voluntarily. Data from each of N users appear in four lines. The first line identifies the user who has registered and provided information about classmates. The second, the third and the

fourth lines list classmates of the user in school, college and university respectively. The input is illustrated in sample input. The entire input set terminates with an input `0' for each of K and N. Output For each test case in the input print two lines. The first line contains the test case number K and the next line contains the seven statistics mentioned above in the order in which they are listed, viz., S, C, U, SC, SU, CU and SCU. The output is illustrated in sample output. Sample Input 13 31 42 90 18 19 34 15 19 42 13 42 26 80 90 53 17 20 31 79 11 14 15 19 79 80 34 80 19 00 Sample Output 1 10 4 4 3 3 2 2 5. Write a C program to shutdown or turn off computer 6. Write a program to execute system command- dir *.bak. user should enter blank line to exit 7. Data compression is the process of transforming a body of data consisting of a character stream to a smaller size using certain codes, from which the original data can be restored by decompression. There exist many complex data compression algorithms that can sometimes achieve phenomenal compression. A simple dictionary-based compression technique is stated below. The technique is based on the concept of a dictionary that stores repeating code sequences as words. You are required to write a program to compress a given body of data using the technique and decompress the data when required. Assume that the complete set of distinct characters present in the body of data (including the blank character if present) is also given as a string of characters. The dictionary is organized as an indexed list of words. A word in the dictionary is associated with its index (a distinct nonnegative integer), its coded representation (an

ordered pair of integers) and its length (the number of characters in the word). Initially each character in the given string is stored in the dictionary as a word in the order in which it appears in the string. The index of the first entry in the dictionary is assumed to be 0. If the index of an entry in the dictionary is n then the index of the next entry is (n + 1). The entire body of data is encoded replacing each character by its index in the dictionary. The encoded data is compressed successively creating a new word in the dictionary by concatenating two existing words and encoding each appearance of the new word in the body of encoded data by its index until no further compression is possible. Since a new word is created by concatenating two existing words, each word in the dictionary is encoded as an ordered pair of integers (i, j) where i and j are respectively the indexes of the two existing words, which appear in the left and in the right, to form the word by concatenation. Each distinct character stored initially in the dictionary, say with index k , is encoded as (- 1, k) . The process of successive compression is stated below: Scan the encoded data from left to right and select the most frequently occurring word W. If there are two or more such words then the tie is broken first by selecting words having the largest length and then by selecting the word having the smallest index. a) Let w be a new word that can be formed by concatenating an existing word, say E, to the left or to the right of W, i.e., the word w is either EW or WE and it may also be the word WW. Find the number of times each w occurs while scanning the encoded data from left to right. b) Select the most frequently occurring new word w with frequency two or more. If there are two or more such words then the tie is broken first by selecting words w having the largest length, then selecting E with the smallest index and finally if necessary selecting the prefix EW instead of the postfix WE. c) Add the selected new word w in the dictionary. Let its index be n. Scan the body of encoded data from left to right and replace each occurrence of w by its index n. d) In case no w exists, consider the next possible W and repeat the process until no new word can be created. e) At the termination of the process the body of encoded data represents the given body of data in compressed form and the dictionary contains all words used in the compressed data. The compressed data may be decompressed using the dictionary and the given string of characters. Input The input may contain multiple test cases. For each test case, the first line contains the test case number p and the option number q, which is either 1 (for compression) or 2 (for decompression). The second line gives a string of complete set of distinct characters that appear in the body of data. The string terminates with the character `$'. For data compression the body of data follows the second line in one or more lines and is terminated by the character `$'. For decompression the dictionary and the body of encoded data follow the second line. A blank line separates the dictionary and the body of encoded data. Each

word in the dictionary is given in a single line in the order it appears in the dictionary. The line contains the ordered pair of integers representing the word in encoded form. The body of encoded data appears in one or more lines as a sequence of integers. The character `$' terminates the body of encoded data. The entire input set terminates with an input `0' for each of p and q . The input is illustrated in sample input. Output For each test case the first output line contains the test case number p and the option number q. If the option is data compression then the output is in the form of input for decompression. For decompression the body of decompressed data terminated by the character `$', follows the first output line. The output is illustrated in sample output. Sample Input 11 abc$ abcbaacbabbcaccabca$ 22 01 $ -1 0 -1 1 -1 2 01 32 02 410513125240$ 31 01 $ 01 100 1011 0 01 0$ 00 Sample Output 11 abc$ -1 0 -1 1 -1 2 01 32 02 410513125240$ 22 01 100 1011 0 01 0$ 31 01 $

-1 0 -1 1 -1 2 01 32 02 410513125240$ 8. The little Jerry is now developing a game. You know developing game is a complex thing as there are many challenges involved. For example little Jerry is now stuck with some geometric pattern and asks for your help. To help him you do not need to know every detail of the game, only information of the particular frame should suffice. Here it is: Two circles are attached with the wall. They are fixed. A line is attached to the circles in such a way that it touches both the circles and each of the touching points has lower Y coordinate than that of the corresponding center of the circle. Now another circle is dropped on the set up from above (higher Y coordinate). The circle will fall along the Y axis with a constant velocity of 1 unit per second until it touches the line. When it touches the line, it starts to rotate along the line towards the circle that has lower Y coordinate touching point with a constant angular velocity of 1 revolution per second. When it touches the circle at the end, it stops. If both the touching points have same Y coordinate, i.e. the line is parallel to the X axis, then the falling circle stops as soon as it touches the line. Now given the setup, you need to find the time after which the falling circle will stop.

Figure 1: Initial Setup, the circle starts falling

Figure 2: The circle touches the line and starts to rotate

Figure 3: The circle touches the circle in the end and stops Input The first line of the input will denote the number of cases T (T 10000). Each of the test cases will contain 3 lines describing 3 circles. The first two lines will give information of the circles at the ends and the 3rd line will describe the circle that will fall. Each of the circles are described with 3 integers x, y and r (-100000 x, y 100000; 0 < r 100). You are assured that the falling circle will always touch the line first and will drop between the fixed circles. Also, note that the falling circle will not bounce, no matter what its height is. Output For each case output the case number and the time required in seconds. Absolute difference less than 1e-6 will be considered correct. Sample Input Output for Sample Input 2 005 100 1 6 50 60 10 005 100 1 8 50 60 10 Case 1: 55.000000 Case 2: 56.511165

9. Write a program in c to find the probability of getting 2 heads when 5 coins are tossed simultaneously. 10. WAP to find the area under the curve of sinx in multiples of pi. 11. WAP to find the second order differential of a 2nd degree polynomial equation.

12. WAP to find the value of the normal force for a box placed on a plain inclined at 30 degrees. 13. WAP to fin the center of mass of a solid sphere. 14. WAP for a traffic light to work 24hrs. 15. Input: Standard Input Output: Standard Output Find the result of the following code: unsigned long long allPairLcm(int n){ unsigned long long res = 0; for( int i = 1; i<=n;i++) for(int j=i+1;j<=n;j++) res += lcm(i, j);// lcm means least common multiple return res; } A straight forward implementation of the code may time out. Input Input starts with an integer T ( 25000), denoting the number of test cases. Each case starts with a line containing an integer n (1 n 5*106). Output For each case, print the case number and the value returned by the function 'allPairLcm(n)'. As the result can be large, we want the result modulo 264. Sample Input Output for Sample Input 4 Case 1: 2 2 Case 2: 1036 10 Case 3: 3111 13 Case 4: 9134672774499923824 100000 16. WAP to sort an array using SHELL sort 17. WAP to Check if mouse support is available or not. 18. WAP to Display mouse pointer in textmode

19. WAP to Display mouse pointer in graphics mode. 20. WAP to hide mouse pointer. 21. WAP to Current position of mouse pointer. 22. WAP to determine which mouse button is clicked . 23. WAP to restrict mouse pointer in rectangle . 24. WAP to restrict mouse pointer in circle . 25. Given a 3 x 4 grid of distinct letters. The letters in the grid are rearranged so that no letter remains in the same row or in the same column. In addition it is known that, in the new arrangement, certain given sets of letters appear in the same row or in the same column. You are required to write a program to determine the new arrangement of letters in the grid, assuming that there exists such a unique arrangement As an illustration, consider the arrangement given on the left. Assume that after rearrangement of letters no letter remains in the same row or in the same column. In addition, assume that letters in each string of letters: LAJ, KIG, HDB, ACJ and EIG appear in the same row while the pair of letters appearing in each string: KL, AH, ID, GB, JD and LF appears in the same column. On the basis of this information the program should find the new arrangement shown on the right.

Input The input may contain multiple test cases. Each test case contains three lines. The first line gives a sequence of three strings of distinct letters, each of length four. The j-th letter in the i-th string (i = 1, 2, 3; j = 1, 2, 3, 4) represents the letter in j-th column and i-th row of the grid. The second line gives a sequence of strings of distinct letters, each of length three. The letters in each string appear in the same row, after rearrangement. The third line gives a sequence of strings of distinct letters, each of length two. The letters in each string appear in the same column, after rearrangement. A blank character separates two consecutive strings in a line. The input terminates with an input line containing `0' for a test case.

Output For each test case, print in one line, a sequence of three strings of distinct letters, each of length four. The j-th letter in the i string (i = 1, 2, 3; j = 1, 2, 3, 4) represents the letter in j-th column and i-th row of the grid after rearrangement. Use a blank character to separates two consecutive strings in a line. Sample Input ABCD EFGH IJKL LAJ KIG HDB ACJ EIG KL AH ID GB JD LF 0 Sample Output KEIG LAJC FHDB 26. Modern writers do not use pens to write books. They enter the text directly on to the home PCs using MS Word and edit the text when necessary. After entering the text for a new book, a famous novelist desires to have a major rearrangement of the text he has prepared. He has identified passages in the text and numbered these passages. However the passages are not in proper sequence. He wants to use the minimum number of cut and paste operations of MS Word to edit the text and put the passages in proper order. He may do the operation either with one passage or with a number of passages occurring in a sequence. He needs a program for this purpose. The following example illustrates his problem. In order to edit the text containing 6 passages in the sequence P2, P4, P1, P5, P3, P6 so that the passages appear in the text in the proper sequence viz., P1, P2, P3, P4, P5, P6 he needs at least 2 cut and paste operations: c u t P 1 a n d p a s1t.e before P2 to get P1, P2, P4, P5, P3, P6 and 2c.u t P3 and paste after P2 to get P1, P2, P3, P4, P5, P6.

Can you write a program for him? Input The input may contain multiple test cases. For each test case, the first line contains two integers, the case number c and the total number n of passages. For simplicity, passages are represented by integers 1, 2,..., n. The input sequence of passages is given in n lines, each line containing one integer in the order in which the passages appear in the text before editing. The entire input set terminates with an input `0' for c.

Output For each test case in the input, print the test case number c and the total number k of cut and paste operations needed for the rearrangement of passages. Print the given sequence in one line. In the next k lines print successive changes in the sequence of passages due to application of k cut and paste operations. Print a blank line between outputs of two test cases. Sample Input 16 2 4 1 27. Assume that there are n vectors each of size 2k. Number the dimensions of the vector as 1, 2,..., 2k. Define the badness of a vector by the sum of the absolute values of the k differences of the k consecutive pairs. For example, the badness of the vector {1, 4, 3, 2} is | 14| + | 32| = 4. The badness of the set of n vectors is the cumulative badness of the elements. However, the dimensions can be shuffled to produce another vector. For example, the above vector can be shuffled to produce {2, 1, 4, 3} which improves the badness to 2. The problem is to choose a shuffling of the vectors such that the cumulative badness is minimized. Note that the shuffling must be consistent and must be applied to all the vectors in the set, i.e., if two columns are interchanged, they must be interchanged for all the vectors. Input The input may contain multiple test cases. First line of a test case contains two information. First one is the number of vectors while second one tells about the length of the vector. If the number of vectors is n, each of the length say, 2k, then next lines provide the vectors. The input terminates with a line containing `0' as input. Output Output the total badness value followed by the shuffled vectors. Sample Input 24 1542 2233 Sample Output 4 2154 3223

28. Delete the least number of integers from a given set of integers so that the product of the remaining integers in the set is a perfect square. In case there is more than one solution then find the solution that gives the largest perfect square. Assume that each integer contains five or less number of digits. The total number of integers in the given set is twenty or less. You are required to write a program for a problem as simple as this. Input The input may contain multiple test cases. For each test case there is a single input line. The line contains the given set of integers. The input terminates with a line containing 0 as input. Output For each test case there is only one output line. The line simply prints the integers to be deleted in ascending order. There are two special cases; print output for these cases as indicated below. Case 1: No integer is to be deleted: Print `0' as output. Case 2: All integers are to be deleted: Print all integers in ascending order. Sample Input 2 3 12 18 24 12 10 15 18 4 12 10 15 10 12 15 0 Sample Output 24 0 10 12 15 10 12 15

29. Professor Anupam Shukla is fond of playing with matrix. One day in his class he has defined a matrix which is filled up with scores but these scores can be positive, negative or zero. Professor Shukla has called the position of an element in a matrix by cell. Every cell is connected to its right, left, top and bottom only if the corresponding cell exists. Score of a connected component is the sum of scores in the cells of the connected component. Professor Shukla has asked his students to write a program to find a connected component of cells from the matrix that has the highest aggregate score. If there are two or more connected components with the same maximal score, return the one with the largest size, i.e., the one with the largest number of cells. Input The input may contain multiple test cases. First line of the input of the program will be the dimensions of the matrix and the scores are given on the next line onwards.

Output The output should be the total score followed by the matrix showing the cells in the connected component. Other cells should be represented by `X'. Sample Input 34 -1 4 -6 7 3 2 -9 -9 -3 0 -5 4 Sample Output 10 X 4 -6 7 32XX X0XX

30. Suppose there are some groups of friends who all believe fervently in numerology. They decide to choose the best group among them by aligning the vowels of their names. In order to account for mismatches in the number of vowels, a special symbol `-' is introduced that can augment the total number of vowels to make them the same. A symmetric matrix of size 6 x 6 is conceived to encode the scores of matching each vowel plus the gap to every other vowel and the gap. Even though the scores can be positive and negative, certain constraints apply. For example, the score of a vowel with itself is positive, while that of a gap with any character (including another gap) is negative. When aligning their names, the column-wise scores are accumulated. For each column, the score is the cumulative of the pair-wise scores. For example, if the alignment of vowels of three names AEI, AO and EU is AEI A-O -EU then the score for the first column is score(A, A) + score(A, -) + score(- , A), while that of the second and third columns are score(E, -) + score(- , E) + score(E, E) and score(I, O) + score(O, U) + score(U, I) respectively. The total score is the sum of the scores of the three columns. Write an algorithm to compute the maximum possible score of a group of friends. Assume that there are 3 to 5 friends in a group. Input The input may contain multiple test cases.

The first line contains the information about the number of friends in the group. If the number is n, then the next n lines contain the names of these n friends. Next six lines provide the 6 x 6 score matrix ordered according to A, E, I, O, U, -. For example, score(I, O) is the value in the 3-rd column of the 4-th row. The input terminates with a line containing 0 as input. Output Output the maximum total score followed by the corresponding alignments.

Sample Input 3 SATTEKI DRY ANMOL WRY SEMI FRY +3 +1 +1 -1 -2 -4 +1 +5 +2 -3 -3 -4 +1 +2 +3 +0 -1 -4 -1 -3 +0 +3 +2 -4 -2 -3 -1 +2 +4 -4 -4 -4 -4 -4 -4 -4 0 Sample Output -2 AEI -AO -EI

31. Assume, in a forest there are n trees and i-th tree is at position i, for i = 1...n. These trees are having different heights. Let us assume that the tree i is having nonnegative heights h feet. One day the forester has decided to trim the heights or uproot the trees to arrange the rooted trees with respect to their heights. That is, at the end of the operation, rooted trees satisfy the property of hi < hj for i < j. Note that if one uproots a tree, then it cannot be placed back in any place and hence it is no longer in the forest. The problem is to determine is the minimum cutting of wood required to make sure that all remaining trees satisfy the height property. Input The input may contain multiple test cases. Each test case contains a sequence of n integers to indicate the heights of n trees in the forest. The i-th integer indicates the height of the i-th tree. Output

For each test case, output is the total length of the wood cut. It is followed by a line which tells the amount of cut from each tree, i.e., i-th element in the line tells the amount of cut in the i-th tree. Next line contains the information about the final height of each tree which means that i-th element in that line tells the current height of the i-th tree. If a tree is uprooted, then mark its final height as `x'. Sample Input 25127 Sample Output 3 00120 25xx7

32. Mr. Walker is a person who is known for his ability to walk fast. He accepts an attractive offer to get as much free land as he can cover by a walk on an open uneven huge piece of land within a specified time and following certain conditions. A walk is a sequence of paths, starting at a marked spot on the land and ending at the same spot where the walk starts. The first path in a walk begins at the marked spot and extends in one of the four directions: North (N), South (S), East (E) or West (W). It ends at the point where the direction changes. Each of the other paths in a walk begins at the point where the previous path ends and ends either at a point where the direction changes or when the walk ends. Mr. Walker may change directions, as and when he feels like, depending on the constraint of time and/or quality/quantity of the land he decides to get. When he changes a direction he must keep the direction always to one of the four directions N, S, E or W. Paths are distinct and nonintersecting; for example, a path in E or W direction cannot cross another in N or S direction. Given a walk, you are required to write a program that finds the area of land covered by the walk. Input The input consists of multiple test cases. For each test case there is only one input line. The line gives a walk defined by a sequence of paths. A direction followed, without any space, by a distance represents a path. A direction is denoted by one of the four letters N, S, E or W while a distance is measured in meters and is denoted by an integer. A space character appears between two paths in the given sequence. The input terminates when a line containing `0' appears as a test case. Output

For each test case print the area of land covered by the given walk. Sample Input N3 W4 S8 E4 N5 W6 N2 E9 S6 W3 N4 W6 N2 W3 S4 W5 S4 E14 N6 0 Sample Output 32 30 80

33. Apple trees in a garden form a rectangular grid. A group of monkeys lives on these trees. Not more than one monkey lives in each tree. A monkey feels happy to believe that it is the lord of all apple trees it views from the top of the tree it lives in. However, as the trees are of different heights a monkey can view trees that are not obstructed from its view by other trees. A monkey that views the maximum number T of trees is a lord of lords. The undisputed monarch is the lord of lords that lives in the highest tree. In case two or more lord of lords have the claim to be the monarch then monarchy is disputed. Assume that the ground of the garden is plane; vertical straight lines represent trees; trees are at a distance of unity row-wise or column-wise; and the height of each tree is an integer in the unit of the distance. A tree of height zero in a position indicates absence of a tree on that position. Visibility of a tree R from the top of a tree P depends on heights and locations of P, R and other trees. A tree R is invisible from the top of a tree P if and only if there exists a visible tree Q that lies on the vertical plane containing P and R and is located between P and R so that the top of R is either on or below, the line joining tops of P and Q. Write a program to locate the undisputed monarch, given heights of all trees. Input The input may contain multiple test cases. For each test case, the first line gives two integers m and n representing respectively the total number of rows and columns of trees in the garden. Each of the next m lines contains n integers representing heights of trees in a row. The j th integer in the i -th row represents the height of the tree in i -th row and j -th column of the garden. Assume that the garden contains no more than 200 trees. The input terminates with an input 0 as the first input for a test case. Output For each test case output three integers r , c and T in one line. Integers r and c represent the location of the undisputed monarch, where r is the row number and c is the column number of the tree on which the monarch lives. In case monarchy is disputed, both r and c are zero. The integer T represents the total number of trees visible to a lord of lords.

Sample Input 33 123 456 709 34 4444 4444 4444 1 10 5321642871 0 Sample Output 227 0 0 10 156 34. Bio-HRQ-Comparator is a fully automatic computer based neurological scanning system that scans brains of three persons simultaneously and ranks them 1, 2, 3 with respect to their HRQ (Human Resource Quotient) for a given activity. Bio-HRQ-Comparator has three specially designed chairs each fitted with brain scanning devise. Exactly three persons are to sit on the chairs and just think independently and simultaneously on the best possible solution of a given problem related to an activity for which HRQ is tested. The thinking process continues for a specified duration of time that is dependent on the complexity of the given problem. Bio-HRQ-Comparator captures the thinking process and ranks them with respect to their HRQ without any further scrutiny. Through rigorous testing and analysis, ranking by BioHRQ-comparator has been found to be so precise that no two ranked persons are identified to have different rank order or found to have the same HRQ. The system has the potential to replace the traditional method of selection of candidates through interview, where the basic problem is to arrive at total ordering and ranking of a given set of n (assume n 20 ) candidates with respect to their HRQ for a specific job. It is proposed to select arbitrarily k sets of three candidates each and rank candidates in each set using Bio-HRQ-comparator hoping that total ordering and ranking of candidates can be done successfully. However it is not always possible to arrive at total ordering and ranking of all n candidates using arbitrarily selected k sets of candidates. You are required to write a program that either ranks all n candidates, if possible, using the k results obtained so far or determine the minimum number m of additional BioHRQcomparator testing required for determining the total ordering and ranking of all n candidates. In case m additional testing are required, the program should identify m sets of three candidates each, for additional Bio-HRQ-comparator testing. Assume for simplicity that a candidate is not required to appear more than twice for additional testing.

Input Input may contain multiple test cases. Each test case contains two lines. The 1-st line gives n and a string of n letters. Each letter in the string identifies a candidate and letters appear in an arbitrary order. The 2-nd line gives k results of Bio-HRQ-comparator testing. The first field is the integer k and it is followed by k strings of three letters each representing k results. The three letters in a string appear in order of ranks 1, 2 and 3 of candidates represented by the letters. Input terminates with a line that contains `0' (zero) as the first and the only character. Output For each test case, print output in one line. The first field in the line gives the integer m . If m is equal to 0 then a string of n letters follows it; the string represents the total rank order of all n candidates. Otherwise m strings each of length three follow the integer m. Each string contains either three letters or two letters followed by an asterisk (*). Each letter identifies a specified candidate while an asterisk represents an option to have any candidate. Letters in a string appear in alphabetic order and strings appear in lexicographic order. Sample Input 5 axdpf 3 adf xdp axp 5 xapfd 3 afd xdp axf 7 adgbnem 4 aem egn dgm emb 0 Sample Output 1 fp* 0 axfdp 2 ade bmn 35. Chain shopping is a new scheme introduced at a Mall to promote sale. Mall offers normal discount on every item. Under the scheme a customer makes a list of distinct items to be purchased. The list is called a purchase chain. For the k -th item in the chain Mall offers k times the normal discount. This policy attracts customers to form long judicious chains. Assume that an item under sale is identified by an integer ID and normal discount D offered for an item is an amount in whole number. Chain shopping is permitted under certain conditions. Any one of the available items may be included as the first item in the purchase chain. However for any other item in the purchase chain option is dependent on the previous selection. For each item ID Mall displays prominently a list P(ID) of next potential items. If ID is in the chain then the next item could only be any one of the items listed in P(ID) . For example if Mall has four items with ID 24 29 61 81 and next potential items P(24) , P(29) , P(61) and P(81) are

respectively 24: 29 61 29: 24 61 81 61: 24 81 29 81: 24 61 then the chain of three items 61 81 24 is valid while the chain 61 24 81 is invalid. Write a program to print purchase chain(s) of specified length L , for which the total discount MD is maximum, given ID and D for each item under sale and all lists of next potential items. Input Input contains multiple test cases. Each case contains three lines. The 1-st line gives an integer specifying L. The 2-nd line gives a certain number (assume 20 or less) of pairs of integers in an arbitrary order. Each pair represents ID and D in order, for an item under sale. The 3-rd line gives all lists of potential items in the form of a string of integers, space and colon (:). An integer n followed by colon identifies the beginning of a list. Integers separated by space that follow colon, identify items in the list. Either the end of the line or the beginning of another list indicates the end of a list. Input terminates with an input `0' as the first input for a test case. Output For each test case the 1-st line contains two integers N and MD. Integer N is the total number of purchase chains for each one of which the total discount is MD. Each of the following N lines contains one chain and chains appear in lexicographic order. Sample Input 3 24 30 81 20 29 40 61 50 24: 81 29 81: 24 29 61 29: 81 61: 81 24 4 24 20 29 15 61 10 81 5 24: 29 61 29: 24 61 81 61: 24 81 29 81: 24 61

Sample Output 2 230 29 81 61 61 24 29 1 150 81 61 29 24 36. Development of unused land is an essential first step for creation of infrastructure. An entrepreneur ventures into a project for creation of a state-of-the-art health-care centre in a city. Government is prepared to allocate under certain conditions, a part of an unused block of land for the project. The block exists in the form of an MN grid of square plots each of unit area. The entrepreneur has estimated for each plot, the cost of development in certain

unit and rounded it to an integer. He requires for the project, a total number of K connected plots. However he is allowed to select only a rectangular/ square block of plots so that at least one side of the selected block either coincides with or is a part of a side of the existing block. In addition, on removal of the selected block, plots in the existing block should remain connected. Given the cost of development for each plot in the grid and the total number K of plots to be selected, write a program to select all feasible blocks (say b in number), for each one of which the total cost of development C is the least. Tables below illustrate the selection of all 3 feasible blocks (b = 3) , each containing 4 plots (K = 4) with least total cost of development (C = 47) . Integers on the grid represent cost of development of plots and shaded plots identify selected blocks.

Input Input may contain multiple test cases. For each test case the first line gives three integers M , N and K as defined above. Each of the next M lines contains N integers; the j -th integer in the i -th line represents the cost of development of the plot in i -th row and j -th column of the grid. Input terminates with a line containing `0' as the first input for a test case. Output For each test case, print in the first line, the least total cost of development C and the total number of feasible blocks b. The first line is followed by b more lines; each line contains two pairs of integers identifying a feasible block. The 1-st pair identifies the first and the last row of the selected block, while the 2nd pair identifies the first and the last columns of the block. The lines appear in lexicographic order. Sample Input 344 3 20 29 6 21 9 6 11 7 10 25 5 343 3 20 29 6 21 9 6 11 7 10 25 5 0 Sample Output 47 3

2312 2334 3314 22 1 1344

37. Editing of original version of a document produces the final version after certain corrections, insertions, deletions and/or reorganization of text. The original as well as the final version of the document may be considered as a string of only case-sensitive letters, digits, space and standard punctuation symbols: comma, full stop, semicolon and colon. In order to avoid confusion the character `#' is used to represent a space character in a string. Often the two versions contain common sub-strings of characters intermixed with uncommon substrings scattered throughout the document. A publishing house wants to have a computer program that will identify the difference between the two versions of a document, given the two versions as input. You are required to write a program for the publishing house. The difference between the two versions is considered to be a single string containing reduced forms of original and edited versions, separated by the underscore (_) character. The reduced forms of two versions are obtained by deleting successively the longest common sub-strings of length two or more from the two versions simultaneously until no more common sub-strings exist in the two versions. In case there exist two or more longest common substrings, the rightmost longest sub-string in the original version is selected first for deletion. If the selected sub-string in the original version occurs more than once in the edited version then the right most sub-string is selected for deletion. Input Input may contain multiple test cases. Each test case contains two lines. The first line contains the original version while the second line contains the edited version of the document. Assume that each version contains not more than 250 characters. Input terminates with a line containing `#' as the first input for a test case. Output For each test case, print output in one line. The line contains two fields separated by a space. The first field is an integer representing the total number of common sub-strings deleted; the second field is the string representing the difference between the two versions. Sample Input docu#giori#nal#,#ment. Original#,#document#. ready#and#explore explore#and#ready gty#frsirheir:sig eir:sigtyfr#ssirh #

Sample Output 5 o#._O. 3_ 4 g_s 38. Full connectivity of network of roads in a new developing industrial city does not exist. Due to existing partial connectivity it is not always possible to reach a location on a road from another location on another road. It is considered desirable to connect all unconnected existing network of roads with minimum cost. You are required to write a program to determine the total minimum cost required for connecting all unconnected roads. At the time of development of each sector, axes parallel roads are constructed in the sector, parallel to either of the two mutually perpendicular axes passing through the city center. The x -axis extends from west to east while the y -axis extends from south to north. The roads extending from west to east are called Streets while the roads extending from south to north are called avenues. A pair of points with the same y coordinate identifies the extremities of each street. Likewise a pair of points with the same x -coordinate identifies the extremities of each avenue. Assume for simplicity that integer coordinates represent each extremity and the cost of construction of roads is equal, in certain unit, to the length of the road constructed. For illustration consider the connectivity of the network of roads shown in the figure below, with three streets S1, S2, S3 and three avenues A1, A2, A3. The network is not fully connected. However, connection with minimum cost can be established by construction of additional roads at locations indicated by block arrows: a) Extend either S1 or S2 and join the two streets constructing a new avenue. b) Extend the avenue A2 and connect it to S3.

Input Input may contain multiple test cases. Each case contains two lines. The first line identifies all streets in an arbitrary order while the second line identifies all avenues, again in an arbitrary order. Each street is represented by three integers: the x -coordinate x0 of the extremity towards west, the x coordinate x1 of the extremity towards east and the common y -coordinate yc . Likewise, each avenue is represented by three integers: the common x -coordinate xc , the y -coordinate y0 of the extremity towards south and the y -coordinate y1 of the extremity towards north. Input terminates with a line containing `0' as the first input for a test case. Output

For each test case, print the total minimum cost required for connecting all unconnected roads. Sample Input 6 20 0 1 15 10 -9 -2 8 -7 2 10 8 3 11 19 -4 2 -6 20 10 -16 12 -6 -12 12 4 -8 -4 8 8 -12 8 0 Sample Output 8 2 39. Game U-turn is a card game of patience, played by a single player. Given a sequence of cards with some cards face up and others face down at arbitrary positions, a player is required to perform a series of operation called U-turn to make all cards face up without altering positions of cards in the sequence. A U-turn operation is performed on a sub-string of cards of any length to u-turn the face of each card in the sub-string, i.e., if the face of a card is up then put it down and if it is down then put it up, without altering positions of cards in the sub-string. The effort of a U-turn operation is the length of the sub-string on which the operation is performed. The series of U-turns should be such that the effort of each U-turn operation is distinct and the total effort of the series of operations is minimum. Write a program to find the total minimum effort required to make all cards of a given sequence face up using a series of U-turn operation. Assume that the sequence of cards is represented by a string of 0's and 1's where a zero represents a card with face up and a one represents a card with face down. Input Input may contain multiple test cases. Each test case has a single input line containing a string of 0's and 1's. The length of the string is fifteen or less. Input terminates with a line containing `0' as the input for a test case. Output For each test case, print the total minimum effort required. Sample Input 1000101 001100010 1010100000 0 Sample Output 9

3 7

40. Homework to primary school children often becomes primary home engagement for parents. In order to lessen the burden of parents a software firm proposes to develop a package that includes solutions to problems on Arithmetic, which are commonly given as homework. As a programmer of the software firm you are required to write a program to solve such a problem. The problem is to add triplets of integers from a given set S of n( 30) distinct positive integers and Determine all K subsets {a b c d e f} of six distinct elements in S so that the sum of three elements in the subset, say (a + b + c) , is equal to the sum (d + e + f ) of the other three. For example, given the set S = {1001 2001 3001 4001 5001 6001 7001} there exists exactly three subsets (K =3) : {1001 2001 3001 4001 5001 7001} , {1001 2001 3001 5001 6001 7001} and {1001 3001 4001 5001 6001 7001} each one of which satisfies the stated condition. Input Input may contain multiple test cases. Each test case contains two lines. The first line gives two integers: n , the total number of elements in S and I , an indicator that indicates the output format. The indicator I , is either 0 or 1. The second line gives n elements of S in an arbitrary order. Input terminates with an input `0' as the first input for a test case. Output For each test case, print output in either of two formats. If the indicator I is 0 then print only the total number K of subsets in one line. Otherwise the line is followed by K more lines each containing elements of a subset. The elements of each subset appear in ascending order and the subsets appear in lexicographic order. Sample Input 60 50 22 87 180 65 115 71 1001 2001 3001 4001 5001 6001 7001 80 12 20 35 38 46 23 18 58 0 Sample Output 0 3 1001 2001 3001 4001 5001 7001

1001 2001 3001 5001 6001 7001 1001 1 4001 5001 6001 7001 4

41. Here is a simple puzzle on numbers. There are n numbers, each of which is of k (k n) distinct and significant digits. When the numbers are lined up in n rows keeping the digits in k columns, the n digits that appear in each column are also distinct. The sum of the numbers is known to be S. One digit from each number is removed so that not more than one digit is removed from each column. The digits removed are all distinct. Thus n incomplete numbers are formed with remaining digits keeping digits in the original order. Given the incomplete numbers and the sum S, what are the original numbers? Can you write a program that solves the simple puzzle? The program should find all possible solutions. Input Input consists of multiple test cases. For each test case data is given in one line. The line contains the case number c, the given incomplete numbers followed by the sum S. A space separates two consecutive fields in input. Input terminates with an input 0 for the case number c. Output For each test case, display output in one or more lines. Each line contains the case number c and a possible solution. A solution consists of the original numbers in the order in which the incomplete numbers appear in input. In case it is not possible to solve the puzzle, assume the solution to be 0 and display output accordingly. Sample Input 1 6 8 174 2 53 81 817 3 3 4 130

0 Sample Output 10 2 536 281 3 36 94 3 83 47 42. The Nobel Prize of Kabiguru Rabindranath Thagore was stolen from a museum of Viswa Bharati University in West Bengal. The Central Bureau of Investigation (CBI) has been assigned the job to investigate the crime and recover the prize. CBI has identified some suspects and linked each one of them to a distinct subset of a set of clues. Let there be p suspects and q clues. Integers 1 to p identify suspects while q distinct lettercodes identify clues. The clues are of varying importance. The alphabetic order of lettercodes determines the priority order in the clues; letter-codes `a' to `z' vary from highest to lowest priority. Let L0 be the set of all suspects. Based on a clue ` ', a subset L of L0 may be split into two disjoint subsets L+ and L- . The subset L+ includes all elements of L that are linked to a subset of clues containing ` ' and L- includes all other elements of L. Let n, n+ , and ndenote respectively the total number of elements in L, L+ and L- . The discriminatory power of a clue ` ' to discriminate suspects in L is defined by =- (| n+ - n- |) Let L* denote a set of disjoint subsets of L0, each subset containing two or more elements. The discriminatory power of a clue ` ' to discriminate suspects in subsets contained in L* is defined to be the sum of all's corresponding to each subset in L*. CBI wants to select a set D of dominant clues so that the presence or absence of some or all of these clues can identify each suspect uniquely. The selection is to be done in stages. Let L* contain only L0 initially. At each stage of selection a clue ` ' with highest discriminatory power is selected. Selecting the clue ` ' with highest priority breaks tie, if any. After a selection of ` ' each L in L* is split into disjoint subsets L+ and ` L- ' all resulting subsets with less than two elements are dropped from L*. The process of selection continues until L* becomes empty. All the clues thus selected form the set of dominant clues D. You are required to write a program to find the set of dominant clues D. Input Input may contain multiple test cases. For each test case input is given in one line. It contains an integer k representing the case number and a certain number of strings of clues. The i-th string represents the subset of clues to which the i-th suspect is linked. A space separates two consecutive fields in input. Input terminates with an input 0 for the case number k. Output For each test case, present output in one line. The line contains the case number k and a string of letters. The letters in the string correspond to the clues in D and appear in the order of their selection.

Sample Input 1 cbx cpxb bc brc 2 bac adce cbd d 0 Sample Output 1 xpr 2 ab

43. Given a two dimensional array of 0's and 1's, you are required to write a program that recognizes the largest (in area) right-angled isosceles triangle hidden in the array. Assume that each `0' or `1' in the array represents a point on a plane and the distance between each pair of neighboring points row wise or column wise is unity. Assume further that every neighboring pair of 1's, row wise, column wise or diagonally is connected by a line segment. Two line segments emerging from a point, either join together to form a longer line segment or form an angle of 45o, 90o or 135o, thus forming right-angled isosceles triangles. The existence of hidden right-angled isosceles triangles in an array is illustrated in the figure below.

Input Input consists of multiple test cases. For each test case the first line gives three integers: the case number k, the number of rows m and the number of columns n of the given array. A space appears between two neighboring integers. Each of the next m lines gives a string of 0's and 1's of length n; the i-th line gives the i-th row of the array. Input terminates with a value zero for case number k. Output For each test case, display output in one line. The line contains the case number k and the area of the largest right-angled isosceles triangle hidden in the array. The area is a real number with one digit after the decimal point. If a triangle does not exist then output `0.0' as the area. Sample Input 133 101 100 101 246 001001 010101 111111 000001 0 Sample Output 1 0.0 2 4.0

44. A word is a string of two or more letters while a code is a string of one or more distinct words in lexicographic order. Thus a string of letters may represent either a word or a code. An optimum code is a code that contains the maximum number of words. For a given string of letters there may be one or more optimum codes. The optimum code of top priority is the optimum code that appears at the top when all optimum codes are arranged in lexicographic order. Given a string of letters, you are required to write a program that finds the following: m in an optimum code, n represented by the string, -code. Input

Input consists of multiple test cases. For each test case there is only one line of input. It contains a string of at most 100 letters. A line consisting of a single letter terminates input. Output For each test case, present output in two lines. The first line gives the two integers m and n defined above. The next line gives the optimum code of top priority, the top-code. Sample Input aaaaaa words lexicographic a Sample Output 21 aa aaaa 11 words 32 lexic og raphic

45. In an online selection process, a candidate is required to respond True (coded 1) / False (coded 0) to a series of k questions interactively. Questions are offered from a question bank that contains n question-groups numbered 0, 1, 2,...(n - 1). Each question-group

contains a large number of questions of more or less the same difficulty. Each question in a question-group has the same answer, either `1' or `0'. The answer to questions in the i-th question-group is denoted by , i = 0, 1, 2,...,(n - 1). During an interactive session, a candidate is graded after each response and categorized into one of n states numbered 0, 1, 2,...(n - 1) confidentially. At the beginning of a session a candidate is assumed to have score 0 and is in state 0. A candidate in state i is offered a randomly selected question from question-group i. The score of a candidate is increased by one if the response matches with the correct answer . Further the state i is changed to state i0 if the response is `0' and to state i1 if the response is `1'. For a given state i, states i0 and i1 are known and may or may not be distinct or different from i. On termination of a session after k responses, let m be the total score and r be the total number of `0' response. Given a selection process stated above and the total score m of a candidate, you are required to write a program that determines the maximum value of r. Input Input will consist of multiple test cases. For each test case the first input line gives four integers: the case number c, parameters n ( 20), k( 30) and the total score m. Each of next n lines gives three integers; the i-th line gives i0, i1 and for i = 0, 1, 2,...,(n 1). A space appears between any two neighboring fields in an input line. Input terminates with a value zero for c. Output For each test case, display output in one line. The line contains the case number c and the maximum value of r. Sample Input 1343 020 201 210 2352 021 200 211 0 Sample Output 13 23

46. Suppose you have a calculator which has a precision of n decimal digits. The calculator can perform arithmetic on integers containing at most n decimal digits but if some result overflows then it displays only the least significant n digits and ignores the remaining digits. In other words, it computes modulo 10n. You enter a positive integer > 1 with at most n decimal digits with no leading zeroes and press the x2 key which computes the square of the number displayed. Magically, the number displayed remains the same. You have to write a program to find the number that was originally entered. If there is more than one such number possible, your program should find them all. Note that the calculator does not display leading zeroes. Input The input for this problem will be a sequence of positive integers specifying different values of n 1. The sequence will be terminated by a `0'. Assume that the maximum value of n is at most 1000. Output The output should consist of all the possible answers (one per line, in increasing order) for each value of n. Each answer should be written on a separate line as a character string, starting with the most significant non-zero digit without any (leading or trailing) spaces. The answers for different values of input n should be written in the same order as specified in the input. Sample Input 1 2 0 Sample Output 5 6 25 76 47. CHIP company manufactures combinational circuits built using only 2-input AND, 2-input OR and 1-input NOT gates. Circuits can have n (at most 30) primary input wires (labelled from 1 to n) and m (at most 10) output wires (labelled from 1 to m). You are hired to write a program to help automate testing of their hardware circuits. Your program should read, for each circuit to be tested, a description of the circuit and desired values (bit vector) at the m output lines. It should then print how many possible input vectors can produce that particular output. If the desired output cannot be produced by any input combination, print `0'. Input The first line will be number of circuits to be tested. It will be followed by data for each circuit ending with a line containing `-1'. That is data for first circuit, then a

line containing `-1', then data for second circuit and so on. For each circuit, the data contains its description followed by test cases. The first line of the description will contain the number of primary inputs (n) and number of primary outputs (m) for this circuit (2 numbers separated by a space). The next line contains the number of gates (k) used in this circuit. This is followed by k lines (one per gate) describing each gate in the following format. First number is the Gate Number, the second number is the Gate-Type (`1'=And, `2'=Or, `3'=Not), followed by one number for each input wire of this gate showing where that input wire is connected. A negative number (`-4' say) means this input comes from the output of gate 4. A positive number (`3' say) means this input comes from primary input wire 3. After these numbers for input wires, there is one last number indicating whether the output of this gate is connected to some other gate's input (denoted by `0'). or it is a primary output (denoted by n > 0 the number of the output wire). The circuit description is followed by test cases (one per line) for desired values on the output wires. If a circuit has m output wires, a test case will be m numbers (`0' or `1') separated by a single space representing the values at wires 1 to m. The first circuit in the sample input given below implements XOR function on 2 inputs. Output For each test case in each circuit, print one number (on a separate line, no blank lines) which indicates how many possible input combinations can produce that output. Print `0' if the test case output is not achievable with the circuit. Sample Input 2 21 5 1310 2 1 -1 2 0 3 1 1 -4 0 4320 5 2 -2 -3 1 1 0 -1 22 2 11121

48. A substitution cipher is a method used for encoding a plain text message. For every character c in the alphabet, a string f (c) is defined. A plain text message c1c2c3...cn is encoded by concatenating the strings f (c1)f (c2)f (c3)...f (cn) in the same order. You have to write a program, which given the substitution rules and a string, determines whether the string can be obtained by encoding some plain text message using the substitution rules.

Input The input will consist of several test cases. The first line of each test case will specify n, the size of the alphabet for text messages. If n is 0, it indicates end of input. Assume that n is at most 10. The next n lines will specify the values of f (c), one per line, for the n characters in the text alphabet. Assume that f (c) may contain at most 10 characters, each of which is from `a' to `z'. The next line will contain a single integer m, which is the number of strings to be tested with the given substitution rule. The next m lines will contain one string each with at most 10000 characters, each of which is from `a' to `z'.

Output The output for each string tested is `1' if the string is an encoding of some string and `0' otherwise. The output should be written one per line, in the same order as the strings tested. Sample Input 2 aba ab 2 ababa abaab 3 xyz z yyx 2 zyzy yyxxyzz 0 Sample Output 1 1 0 1 49. Trisanku wanted to ascend to Swarga (Heaven) by building a ladder all the way from earth to heaven. He undertook rigorous penance seeking boons from the trinity Brahma, Vishnu and Siva. Pleased by his austerities, the three Gods appeared before him first and gave him the following boon. They asked him to choose three prime numbers (b, v, s) one for each of them and then guaranteed that they would magically ensure that if there was any rung on the ladder at any height h above the ground, they would ensure there were rungs also at

heights b + h, v + h and s + h. Trishanku built only the first rung at a height of 1 feet from the earth and then invoked the boon. Magically many more rungs appeared as promised. Trishanku began the assiduous climb to heaven going up one rung of the ladder at a time. He kept track of various statistics along the way, such as what height he was at and how many rungs he had climbed so far and the sequence of gaps between any two consecutive rungs he had climbed. He maintained all this data in a bulky journal which slowed his progress. Your job is to help Trisanku by writing a program that will eliminate the need to keep such bulky journals of data. Your program should read as input the three prime numbers and then answer the following three types of queries. Given any height n ft above the earth, how many rungs are there in the ladder at or below height n from the earth. a) Given the number n of rungs that Trisanku has climbed, what is biggest gap between any two consecutive rungs he has encountered so far. b) Given a gap value n, after how many rungs from the bottom does this gap appear (if it appears at all) for the first time between two rungs on the ladder. If gap does not appear, print a `0'. c) You can assume that all values given/calculated for these queries will fit in a 32 bit integer.

Input First input line is the number of test cases for the program. The next line is the b v s values (three primes separated by a single space) for this test case. Queries for this test case follow, one query per line. Each query will have 2 numbers separated by a single space. The first number is the query type (1, 2 or 3) and the second number is the value of n for this query. A line with `0' terminates the queries for this test case. Output Output will be one number per line - the answer for each query in the same order as the queries. Ouptut lines should be consecutive with no blank lines between test cases.

Sample Input 2 11 13 17 50. A necklace contains n beads, each of which may be of any one of seven different colors. The beads are arranged arbitrarily in circular order with a thread passing through the center of each bead. The thread is tied up at its ends and the necklace is closed. Unfortunately, the colors of the beads are all mixed-up and may appear in any order. It is your task to rearrange the beads so that all beads of the same color occur together. To do this, you are allowed to cut the thread at any point, remove some beads from either end, put them back

in a different order, and tie up the ends again. The cost of this operation is the number of beads that were removed. You may perform any number of such cut operations. The total cost is the sum of the costs of the individual operations. You have to write a program to find the minimum total cost required for rearranging a given initial necklace so that all beads of the same color occur together. Input The input will consist of several test cases. The first line of each test case will specify n, the number of beads in the necklace. If n is zero, it indicates end of input. Assume that n is at most 100. The next line will contain a character string with n characters, specifying the colors of the beads in circular order. The color may be any one of the characters in the string `vibgyor'. There will no line separating individual test cases. Output The output should be a sequence of integers, one per line, giving the answer for each test case in the same order as the input. There should be no lines separating answers for successive test cases. Sample Input 5 vbyrv 8 vbvvvbbv 0

Sample Output 0 3 51. To encourage healthy student teacher interaction, Mumbai School Board requires each school in Mumbai to make every student in the school play 20 decisive games of chess (draws are not counted) with each teacher in the school each year. Thus every teacher (numbered sequentially from 1 to n) at the end of the year has an integer score which is an even number between -20 (if he lost all 20 decisive games) to +20 (if he won all decisive games) against each student (numbered sequentially from 1 to m). The school submits a 2 dimensional (n rows, m columns, n,m less than 100000) matrix of such teacher scores to the Board every year. The Board then computes an overall evaluation for each school in the following way. It picks some k (less or equal to n) adjacent rows (i.e k teachers numbered consecutively). For each teacher ti who is picked a weight wi is generated by picking any ji (less or equal to m) consecutive students from his row of scores and summing his scores against them. Note that this is done independently for each teacher - that is the number of consecutive students picked may be different for different teachers. The School's overall evaluation is the sum of the weights of these k teachers.

You have to write a program for the Board which will take the data for many schools one by one and compute the lowest possible evaluation for each school. Input The first line gives the number of schools. Then for each school, the first line gives the number of teachers (n) and students (m) in this school (2 numbers separated by space). This is followed by n lines (one per teacher) of scores. Each line has m numbers (separated by one space) which is the scores of that teacher against each of the m students. The data for School 1 is followed (immediately without any blank lines) by data for School 2 and so on. Output Output is one line per school (without any blank lines inbetween) containing one number which is the minimum possible score for that school. Sample Input 2 24 10 -4 -4 10 -4 2 -8 4 26 0 -6 4 -6 -4 4 222222 Sample Output -18 -12

52. A factory produces rectangular sheets of metal of varying dimensions. In order to meet demand quickly, the factory has a very large collection of pre-fabricated sheets of different dimensions which are stored in a storeroom. You are the storekeeper and your task is to arrange the given sheets in the storeroom. The sheets must be placed horizontally along the floor but to save floor area, the sheets can be put on top of each other. However, to ensure stability, a sheet can be put on top of another only if it fits completely inside the sheet immediately below it. Moreover the centers of the two sheets must be vertically aligned and the sides must be parallel. A sheet may be rotated though about its center by 90 degrees to fit inside the lower sheet. You have to write a program which will take the dimensions of the sheets as input and compute the minimum floor area required for storing the sheets, assuming that sheets can be stacked on top of each other as described above.

Input The input consists of several test cases. The first line contains a single integer n which is the number of sheets for this problem. If this is 0, it indicates end of input. Assume that n is at most 200. The next n lines contain two integers each, which are the dimensions of the n sheets. There are no lines separating consecutive test cases. Output The output consists of the minimum floor space required for each test case, in the order in which they are given. There should be no leading spaces or lines separating different cases. Sample Input 2 35 44 3 54 25 44 0 Sample Output 31 30 53. A necklace contains n beads, each of which may be of any one of seven different colors. The beads are arranged arbitrarily in circular order with a thread passing through the center of each bead. The thread is tied up at its ends and the necklace is closed. Unfortunately, the colors of the beads are all mixed-up and may appear in any order. It is your task to rearrange the beads so that all beads of the same color occur together. To do this, you are allowed to cut the thread at any point, remove some beads from either end, put them back in a different order, and tie up the ends again. The cost of this operation is the number of beads that were removed. You may perform any number of such cut operations. The total cost is the sum of the costs of the individual operations. You have to write a program to find the minimum total cost required for rearranging a given initial necklace so that all beads of the same color occur together.

Input The input will consist of several test cases. The first line of each test case will specify n, the number of beads in the necklace. If n is zero, it indicates end of input. Assume that n is at most 100. The next line will contain a character string with n characters, specifying the colors of the beads in circular order. The color may be

any one of the characters in the string `vibgyor'. There will no line separating individual test cases. Output The output should be a sequence of integers, one per line, giving the answer for each test case in the same order as the input. There should be no lines separating answers for successive test cases. Sample Input 5 vbyrv 8 vbvvvbbv 0

Sample Output 0 3 54. A factory produces rectangular sheets of metal of varying dimensions. In order to meet demand quickly, the factory has a very large collection of pre-fabricated sheets of different dimensions which are stored in a storeroom. You are the storekeeper and your task is to arrange the given sheets in the storeroom. The sheets must be placed horizontally along the floor but to save floor area, the sheets can be put on top of each other. However, to ensure stability, a sheet can be put on top of another only if it fits completely inside the sheet immediately below it. Moreover the centers of the two sheets must be vertically aligned and the sides must be parallel. A sheet may be rotated though about its center by 90 degrees to fit inside the lower sheet. You have to write a program which will take the dimensions of the sheets as input and compute the minimum floor area required for storing the sheets, assuming that sheets can be stacked on top of each other as described above. Input The input consists of several test cases. The first line contains a single integer n which is the number of sheets for this problem. If this is 0, it indicates end of input. Assume that n is at most 200. The next n lines contain two integers each, which are the dimensions of the n sheets. There are no lines separating consecutive test cases. Output The output consists of the minimum floor space required for each test case, in the order in which they are given. There should be no leading spaces or lines separating different cases.

Sample Input

2 35 44 3 54 25 44 0 Sample Output 31 30

55. A small district in a rural area contains a few villages (maximum 15), which are wellseparated from each other. There are no roads in the district but the villagers have created mud tracks between some pairs of villages. There are at most 25 such tracks and between a given pair of villages there is at most one track. Unfortunately, during the rainy season, some tracks may get flooded and become unusable. Each track may or may not get flooded independent of any other track. For every track, the probability that it is usable (not flooded) is given. The district is connected if there is a way to reach any village from any other village using tracks which are not flooded. You have to write a program that is given as input the probability for each track to be flooded. Your program must determine the probability that the district is connected. Input The input will consist of several test cases. For every case, the first line will contain a single integer n, the number of villages. If n is 0, it indicates end of input. The villages are assumed to be numbered from 0 to n -1. The next line will contain m, the number of tracks. The next m lines will each contain 3 numbers, two integers and a fraction, separated by a space. The first two integers specify the villages that are connected by the track and the third number is the probability that the track is usable. This will be a decimal fraction between 0.0 and 1.0, with only one digit after the decimal point. There will be no lines separating consecutive test cases. Output The output for each test case must a single number, written on a separate line for each case. This number must be accurate to 3 decimal places and at most 3 digits after the decimal point should be printed. Sample Input 2 1 0 1 0.3 3

3 0 1 0.5 0 2 0.5 1 2 0.5 0 Sample Output 0.3 0.5

56. It is rumored that many centuries ago, pirates had hidden priceless treasure on a remote island. You are in charge of an expedition to recover the treasure. You land on the island and find a big mountain, inside which a big network of caves has been built. There are narrow passages connecting some of the caves to each other. You find that in every cave either a big `X' or `+' sign is drawn. On searching further, you find an old manuscript giving a complete map of the caves and the passages connecting them. At the bott om is a note which says that the treasure is buried below the ground in some of the caves. The note also says that the marks `X' and `+' are clues to find the caves below which the treasure is hidden. It says that a cave C is marked `X' if there are an odd number of neighboring caves containing the treasure else it is marked `+'. A neighboring cave of C is one to which there is a direct passage from C without going through any other cave. The note also says that the construction of the caves and passages is such that this information is sufficient to uniquely identify the caves below which the treasure is hidden. You have to write a program to find out these caves from the given information. Input The input will consist of several test cases. The first line of each test case will specify n, the number of caves, assumed to be numbered from 0 to n - 1. If n is 0, it indicates end of input. The value of n will be at most 100. The next line will give m, the total number of passages. The next m lines will contain two integers each, specifying the two caves connected by each passage. The next n lines will give the marking on each cave, one per line, from cave number 0 to n - 1. The mark is given as a single character either `X' or `+'. Output For every test case, the output should be the numbers (one per line, in increasing order) of the caves below which the treasure is hidden. Output lines for each case should be followed (immediately, without any blank lines) by the output lines for the next test case. Sample Input 2 1 01 X

+ 4 4 01 12 13 23 + + + X 0 57. Alpha-Triangle is the unique equilateral triangle that is formed by joining each and every word contained in a given set of words. Like all triangles, an Alpha-Triangle has three vertices and three sides. A point with no dimension represents a vertex in the triangle. A side in an Alpha-Triangle has an identity, a length and a direction. It begins with a vertex, continues with a string of letters and ends up with another vertex. The string of letters identifies the side as well as defines the direction from the beginning to the end of the string. It is made up of a sequence of one or more words belonging to the given set. A word, say W , in the sequence is linked to the word appearing next, say N ; the last letter of W is the first letter of N ; however the common letter appears in the string only once. The total number of letters in the string defines the length of the side. Like all equilateral triangles three sides of an Alpha-Triangle are of equal length. Let the length of each side of an Alpha-Triangle be L . A word, used once in a side, cannot be used again either in the same side or in any other side. Each vertex/side has a distinct characteristic. Two sides meeting at one vertex begin with words having a common first letter. Let these sides be `a ' and `c '. In case of another vertex two sides meeting at the vertex end up with words having a common last letter. Let these sides be `b ' and `c '. In the case of the third vertex, of the two sides `a ' and `b ' meeting at the vertex, `b ' begins with a word having the first letter same as the last letter of the last word in `a '. Vertices are placed so that sides `a ' and `b ' have clockwise direction while the third side `c ' has anti-clockwise direction. A triangle with sides `a ', `b ' and `c ', and associated directions are illustrated in the adjoining figure. Write a program to find the Alpha-Triangle for a given set of words. Input The input may contain multiple test cases. For each case there is one input line. The line gives words in the given set in an arbitrary order. A space character separates two consecutive words in the set. Assume that the total number of words in the set is not greater than 20

58. A baby tries to solve the well-known eight-queen puzzle: the problem of placing eight chess queens on an 88 chessboard so that no two queens share the same row, column, or diagonal. The baby understands the concept of row and column quite well but diagonal is not very clear to her. As a result she succeeds placing eight queens on the board so that no two queens share the same row or column but there remains the possibility that some queens share the same diagonal. Given baby's queens (a solution by the baby) and a valid eight-queen solution, it is possible to move baby's queens to positions of queens in the valid solution. Assume that in a single move, a queen can be moved one unit row-wise or column-wise into an unoccupied position. Write a program to find the minimum number of moves required to move baby's queens to positions of queens in the valid solution. The program should be usable for a more general n -queen puzzle where n queens are placed on an nn chessboard, 4 n 16 . Assume that rows and columns of the chessboard are numbered 1, 2,..., n . Input The input consists of multiple test cases. Each case begins with a line containing the integer n . Each of the next two lines contains a sequence of n integers. Integers in the first line represent column numbers of baby's queens appearing in rows 1, 2,..., n respectively. In the same way, the second line contains column numbers of queens in the given valid solution. A space separates two consecutive integers in the sequence. A line containing a zero `0' as the first character follows the last case. Output For each test case, print the minimum number of moves required. Sample Input 4 1234 3142 4 3241 3142 5 53142 53142 5 15243 31425 0 3840

59. A hand of five cards makes a magician famous. The magician takes an ordinary deck of 52 cards and requests a viewer to select a hand of five cards. The viewer hands over these cards to an assistant, who stands far away from the magician so that the magician does not know what cards, are chosen. The assistant returns one of the five cards to the viewer and hands over the other four cards to the magician in a sequence, say 8 , Q , 8 and 3 . The magician identifies the card left behind with the viewer correctly. The magician applies a simple trick. Cards in a deck of 52 cards are totally ordered, first by ordering the suits in alphabetical order of the suits: C: Club , D: Diamond , H: Heart and S: Spade and then by rank A (=1), 2, 3,... , 9, 10, J (=11), Q (=12), K (=13). Since there are only four suits, the five cards selected by the viewer contain at least two cards of the same suit. The assistant gives one card of the same suit to the viewer, call it the hidden card and one another card of the same suit to the magician, and call it the base card. The base card indicates the suit of the hidden card so that the magician is required to know only the rank of the hidden card. Since the rank of the base card is known, the unknown rank of the hidden card can have one of the 12 ranks not known yet. The assistant plays a trick. She selects the hidden card and the base card so that the rank of the hidden card can be obtained by adding at most 6 to the rank of the base card. If the sum after addition turns out to be greater than 13 then the sum (mod 13) is considered to be the rank, otherwise the sum itself is considered as the rank. Since cards are totally ordered the three remaining cards can be identified by L: Lowest, M : Medium and H : Highest ranked cards. The number to be added to the rank of the base card is communicated to the magician by varying the order of the three remaining cards, as per the following table: For example, when the magician receives four cards in the order: 8 , Q , 8 and 3 , she marks 8 as the base card, identifies the order of the other 3 cards as HLM and adds 5 to 8 to get 13. The magician accordingly recognizes the hidden card as K . Write a program for online demonstration of the trick played by the magician. Input The input may contain multiple test cases. For each test case there is only one input line. The line identifies the four cards and the order in which the cards are given to the magician. Two fields, appearing one after another without any space, represent each card. The first field represents the rank while the second represents the suit. For example JD identifies the Jack of Diamond, AS identifies the ace of Spade or 10C represents 10 of Club. A space character appears between representations of two neighbouring cards.

60. Banks offer deposit schemes of various kinds to attract customers. In an r -year progressively reducing recurring deposit scheme (PRRDS) of a bank, a customer is required to deposit progressively reducing amounts every year for r years. Depending on the duration r of the scheme and the total amount T deposited in r years, the bank offers to return on maturity, i.e., after the expiry of r years, an amount R , which is equal to k times the amount deposited in the first year. The bank ensures that the return R looks attractive by making a suitable choice of k ; k being a natural number.

In a PRRDS, the amount to be deposited in each but the last two years is exactly equal to the sum of amounts to be deposited in the next two years. The amounts to be deposited in the last two years, say x in the last year and y in the last but one year, are progressively reducing (x, y > 0;y > x) and are determined so that the total amount deposited in r years is exactly equal to the specified amount T . Assume that all deposits are in whole number of Rupees. Write a program for the bank, so that given r , k and T , the program computes x and y for which the return R is maximum. For example in a 4-year scheme with r = 4 , k = 3 and T = 500 , the progressively reducing recurring deposits 248, 126, 122 and 4, ensures the maximum return R = 744 with x = 4 and y = 122 . Input The input may contain multiple test cases. For each test case there is only one input line. The line gives values of r , k and T . Assume that r is not greater than 20. A line containing a zero `0' as the first character follows the last case. Output For each test case there is only one output line. The line gives the computed values of x , y and R . Sample Input 4 3 500 5 3 10000 6 4 8000 8 5 12000 0 Sample Output 4 122 744 5 1425 12855 1 666 13332 1 363 23635

61. A baby tries to solve the well-known eight-queen puzzle: the problem of placing eight chess queens on an 88 chessboard so that no two queens share the same row, column, or diagonal. The baby understands the concept of row and column quite well but diagonal is not very clear to her. As a result she succeeds placing eight queens on the board so that no two queens share the same row or column but there remains the possibility that some queens share the same diagonal. Given baby's queens (a solution by the baby) and a valid eight-queen solution, it is possible to move baby's queens to positions of queens in the valid solution. Assume that in a single move, a queen can be moved one unit row-wise or column-wise into an unoccupied position.

Write a program to find the minimum number of moves required to move baby's queens to positions of queens in the valid solution. The program should be usable for a more general n -queen puzzle where n queens are placed on an nn chessboard, 4 n 16 . Assume that rows and columns of the chessboard are numbered 1, 2,..., n . Input The input consists of multiple test cases. Each case begins with a line containing the integer n . Each of the next two lines contains a sequence of n integers. Integers in the first line represent column numbers of baby's queens appearing in rows 1, 2,..., n respectively. In the same way, the second line contains column numbers of queens in the given valid solution. A space separates two consecutive integers in the sequence. A line containing a zero `0' as the first character follows the last case. Output For each test case, print the minimum number of moves required. Sample Input 4 1234 3142 4 3241 3142 5 53142 53142 5 15243 31425 0 Sample Output 6 2 0 8 62. Barracks in a garrison are structured in N rows and N columns with certain security arrangements at each row-column position. Most of the positions are well guarded; however certain positions remain weakly guarded. All positions on the boundary, either well guarded or weakly guarded, are considered vulnerable. With respect to a given vulnerable weakly guarded position, positions appearing next to it column-wise/row-wise/ diagonally, are considered vulnerable. Thus for a given vulnerable weakly guarded position there are at most eight vulnerable positions. Positions, which are

neither vulnerable nor weakly guarded, are considered strongly secured. You are required to write a program to find all strongly secured positions in the garrison. Let a zero `0' identify a weakly guarded position and a one `1' identify a wellguarded position. For illustration, in a garrison with barracks in 5 rows and 5 columns, the strongly secured positions are identified below by (1). 01110 10111 1 1 1 (1) 1 1 (1) 0 (1) 1 11111 Input The input may contain multiple test cases. For each case, the first line gives the value of N , which is not greater than 20. The next N lines identify security status of each position in the garrison. The i th line identifies the status in the i th row of barracks, i = 1, 2,..., N . Each line appears as a string of size N , containing 0's and 1's. Each 0 identifies a weakly guarded position while each 1 identifies a well-guarded position. A line containing a zero `0' as the first character follows the last test case. Output For each test case there are two output lines. The first line gives the total number S of strongly secured positions. If S is equal to 0 then there is no further output. Otherwise there is an additional line of output. It identifies all S positions, listing row number and column number of positions in row-major order. The line contains 2S integers separated by space. Sample Input 5 01110 10111 11111 11011

63. .Allocation of platforms to trains is a usual problem in a busy railway station. Trains arrive at a station, halt forspecified times at a platform and finally depart from the platform. This apparently simple process is not so simple particularly because platforms are not always available at the time of arrival of trains. Department of Railways needs a program for allocation of platforms to trains.Let there be p platforms in a railway station. Arrival times of trains are known for a period of one-hour. Times are recorded as integers; each integer represents a time in minutes counted from the beginning of the one-hour period under consideration. Arrival times vary from 0 to 60 while departure times may exceed 60 as

well. On its arrival a train waits in the yard to get the signal to go to a platform. As and when a platform is available a waiting train in the yard with the least halting-time is selected arbitrarily for allocation of a platform. The halting-time of a train is the difference between the departure time and the arrival time. Assume that no extra time is needed for a train to move from the yard to a platform. The availability of platforms and the haltingtime of trains if any in the yard, at the beginning of the one-hour period under consideration, are known.You are required to write a program to find the sum W , of waiting times in minutes for all trains including trains if any waiting in the yard at the beginning of the one-hour period under consideration. The waiting timeof a train is the time the train waits in the yard during the one-hour period under consideration. Input Input may contain multiple test cases. Each test case consists of two input lines. The first line contains a sequence of integers. The first integer in the line is the total number of platforms p .The next p integers represent times when platforms 1, 2,..., p respectively are available for the first time during the one-hour period under consideration. Next k( 0) integers in the line, if any, represent halting-times for k trains waiting in the yard from the beginning of the one-hour period under consideration. The second line contains an even number of integers. Integers in an odd and the next even numbered positions in the line, give the arrival and the departure times of trains. A line containing `0' terminates input. Output For each test case output the sum W defined above. Sample Input 1 15 30 20 35 10 30 45 65 2 15 0 20 35 10 30 45 65 0 3322 64. An organization has a well-structured human resource. The Chief Executive Officer (CEO) is the top boss of the entire organization. He is the most important personnel and has no boss to report. All other personnel in the organization have a boss to report directly. A boss in tern has direct control over a number of subordinate personnel who are ordered according to their importance. A subordinate under the direct control of a boss may or may not be a boss.All personnel including the CEO are ordered totally according to their importance in the organization. A personnel X is considered more important than another personnel Y if any of the following is true: X is the CEO, X is not the CEO but is the boss of Y X and Y have the same boss and X is more important than Y , X and Y have different bosses and boss of X is more important than boss of Y .

Let the organization has n personnel. A personnel is identified by a distinct integer 1, 2,... or n , called the ID of the personnel, according to the order of importance. The most important personnel viz., the CEO has ID equal to 1, while the least important personnel has ID equal to n . A boss may communicate directly to a subordinate in 1 (one) unit of communication time (UCT) while a subordinate requires 2 (two) UCT to communicate with the boss. The organization maintains a list L of all personnel identified by their IDs. A boss appears in L only after all direct subordinates appear in order of their importance. Given L and two personnel X and Y , you are required to write a program that finds the time T in UCT for X to communicate a message to Y . Input The input consists of multiple test cases. Each test case contains data in two lines. The first line gives three integers n , X and Y defined above. The next line gives a sequence of n integers representing the list L . Fields in input are separated by space. The input terminates when a line containing `0' appears. Output For each test case output the required time T as an integer. Sample Input 724 2674531 742 2674531 0 3323

65. Dates are written using varying formats. A consulting firm deals with clients who use in their communications formats stated below for writing dates. 1.Formats for each field: a.Date (d ): one digit as in 4 or two digits as in 04. b.Month (m ): one digit as in 2, two digits as in 02, name in full as in February. c.Year (y ): low order two digits for a year in the current century as in 05 or all four digits as in 1997 or 2005. 2.Order of fields: dmy , myd , mdy or ymd . 3.Delimiters between fields: Any one of the following in a date; Colon (:), Dash (), Dot (.) or Slash(/). The firm maintains communications in chronological order with the most recent communication at the top. It is possible to have more than one communication on the same date. A date is considered to be in standard format if it appears with full name of

the month, significant digits of the date, all four digits of the year and delimiters space and comma, as in the date February 2, 2005. You are required to write a program that converts each date in a given sequence of dates in chronological order, to the date in the standard format. If more than one interpretation exists for a date then select the most recent date. In case a date violates the assumptions stated above, ignore the defective date all together and consider other dates in chronological order. Input Input consists of multiple test cases. Each test case starts with a line that gives the total number n (0 n 20) of dates in the given sequence. The next n lines give n dates in chronological order, the first line containing the most recent date. Input terminates when n is equal to 0. Output For each test case, print dates in standard format on n lines in the order of dates in input. For each defective date, output `?' against the date. Add a blank line to separate outputs of two test cases. Sample Input 3 02-04-05 06/06/06 02.04.2005 2 02:04:23 02:04/23 2 02/February/03 02.April.01 0 Sample Output April 2, 2005 ? April 2, 2005 April 2, 2023 ? February 2, 2003 April 1, 2002

66. Examination halls in a college contain seats in m rows and n columns. There are k (n k < 10) groups of students. Students of each group appear in the same paper; however students of different groups appear in different papers. Groups as well as seats are identified by integers 1, 2,..., k . A student of a group seats on a seat having the same identification number as that of the group. For allocations of seats in a hall following rules are followed: a) Each row contains at most one student from a group.

b) Each column contains an equal number of students of each group. c) No two students of the same group seat in neighbouring positions, i.e., next to each other in the same row, the same column or the same diagonal. Controller of examination sends a team of staff to identify seats in halls following the rules stated above.However after identifying certain number of seats they find it difficult to identify other seats satisfying the rules. So Controller wants a program that can complete a partial allocation of seats in an examination hall. Input Input may contain of a number of test cases. Each test case starts with a line that gives parameters m , n and k as integers. The next m lines give partial allocations of seats made by the staff; the i -th line gives the partial allocation in the i -th row, for i = 1, 2,..., m . A string of length n represents a partial allocation in a row. The j -th character in the string is an integer 1, 2,... or k if the j -th seat in the row is already allocated; otherwise the j -th character is a `#', for j = 1, 2,..., n . A line containing `0' terminates input. Output For each test case, output a complete allocation in m lines replacing each `#' in partial allocation by an appropriate integer 1, 2,... or k and separating two integers in a line by space. If a complete allocation is not feasible then output a line containing `'0. Separate outputs of two test cases by a blank line. Sample Input 545 1### #4## ##2# ###5 ##1# 333 67. Here is a problem on Geometry. A square non-defective alloy steel plate is required to be cut off from a rectangular plate of the same material containing defects at a set of n given points. The defective points (xi, yi) , i = 1, 2,..., n , are identified with reference to a 2-dimensional Cartesian coordinate system. Let two perpendicular sides of the given rectangular plate form the axes of coordinates and the line segment joining the points (0, 0) and (a, b) form a diagonal of the rectangular plate. You are required to write a program that finds the area of a largest square plate that can be cut off from the given rectangular plate so that none of the defective points is inside the square plate. For simplicity consider only the squares whose sides are parallel to the coordinate axes.

Input The input consists of a number of test cases. Each test case contains two lines of data. The first line gives an integer n and two real numbers a , b . These are the parameters defining the total number of defective points and the rectangle itself. The next line gives 2n real numbers specifying x and y coordinates of the n given points. A number appearing in an odd numbered position in the line defines the x coordinate while the next number defines the y coordinate of a point. You may assume that the magnitude of a coordinate is less than 100. A line containing `0' terminates input. Output For each test case output the required area as a real number. Sample Input 4 5.0 6.0 1.0 2.0 2.0 3.0 1.0 3.0 4.0 4.0 2 3.0 4.0 1.0 2.0 2.0 3.0 0 Sample Output 9.0 4.0 68. A sports meet was organized at a ground close to a wide shallow stream. Animals cross the stream at ease, stepping on stones forming a path in a line from one bank A to the other bank B of the stream. Apes are known for their intelligence as well as for their ability to imitate men. Two friendly groups of apes, one white and the other black, live together happily on two banks of the stream. They observed keenly from their home trees, sport events that went on, on the nearby ground. After the meet apes were seen crossing the stream in an organized manner. In fact they were playing, imitating Hop Step & Jump in their own intelligent way. Let there be a certain number of stones forming the path. At a given instant apes position themselves arbitrarily on stones in the path, keeping some stones empty. No two apes are on the same stone. White apes move toward bank A, while black apes move toward bank B until all of them reach the bank in the direction of motion. At no time an ape changes the direction of motion. Let P , Q and # represent respectively a stone with an ape of one group, a stone with an ape of the other group and an empty stone. Thus a string of P , Q and # represents an occupancy of apes on neighbouring stones at a given instant. The movement of an ape is restricted to the following valid moves: Step: An ape on P moves to the next empty stone, changing occupancy from P# to #P in the direction of motion of the ape.

Jump: An ape on P jumps over an ape on Q and occupy the empty stone situated next to Q , changing occupancy from PQ# to #QP in the direction of motion of the ape. Hop Step & Jump: An ape on P hops over an ape on Q to an empty stone and steps on to the next empty stone. Finally the ape jumps over another ape on a Q to occupy the next empty stone. In other words the movement of the ape on P changes the occupancy from PQ##Q# to #Q##QP in the direction of motion of the ape. Reach: An ape on P reaches the destination finally using a Step, a Jump or a Hop Stop & Jump move, considering the destination bank as a stone. Apes cooperate with one another irrespective of the group they belong to. They organize their movements with a clear objective: maximize the total number of Hop Stop & Jump so that all of them reach their respective destinations. You are required to write a program that determines, for a given initial occupancy, the maximum number of Hop Stop & Jump that can be used by apes to reach their respective destinations. Input The input may contain a number of test cases. Each test case consists of a single input line that gives the initial occupancy of apes on stones. The line contains a string of `0', `1' and `#' that begins with `A' (or `B') and ends with `B' (or `A'). A zero (0) represents a stone with a white ape while a one (1) represents a stone with a black ape. A line containing a single `#' terminates input. Output For each test case, output the maximum number of Hop Stop & Jump that can be used by all apes jointly to reach their respective destinations. There could be a possibility of a deadlock when some apes cannot reach their destinations using the valid moves. In such a case output the value `-1'. Sample Input A111####000B B111####000A A#01#1100B B#01#1100A # Sample Output 4 0 -1 1

69. Alias is an assumed or additional name that constitutes a distinctive designation of a person. Consider a set of n persons and assume that each person has k distinct aliases. A person is identified using any one of its k aliases. The nk (= nk) distinct aliases are identified using integers 1, 2,...nk . Integers 1, 2,..., n represent the first aliases of all n persons in an arbitrary order. In general, integers (j - 1)n + 1,(j - 1)n + 2,...,(j - 1)n + n represent the jth alias of all n persons in an arbitrary order, for j = 1, 2,..., k . Persons in the set are totally ordered with respect to a quality characteristic Q associated with each person. Let Q (r) be the value of Q for a person identified by one of its alias r . Given a sufficient number, say m , of inequalities of the type: Q(r) > Q(s) , you are required to write a program to sort all persons in descending order and recognize all aliases of each person in the set. As a simple illustration consider distinct total marks scored by three students in an examination. Each student is identified by any one of three distinct aliases in the Name: {first-name middle-name last-name}. Let integers 1, 2, 3 represent the first names, 4, 5, 6 represent the middle names and 7, 8, 9 represent the last names in an arbitrary order. Let Q(r) be the total marks of student r, r being an alias. Given the following inequalities: Q(6) > Q(1), Q(9) > Q(4), Q(5) > Q(8), Q(2) > Q(9), Q(7) > Q(3), Q(9) > Q(3) , one can conclude that the names of students appearing in descending order of total marks are {2 6 7}, {1 5 9} and {3 4 8}. Input The input may contain multiple test cases. For each test case the first input line gives the parameters n , k and m . The second line contains m inequalities represented by 2m integers. An integer r occurring in an odd numbered position in the line and the integer s occurring in the next even numbered position, represent the inequality Q(r) > Q(s) . Assume that nk is less than 100 and each integer in the second input line is of two digits, including a non-significant 0 when required. The input terminates with a line containing 0 as input. Output For each test case print n lines giving k aliases of each person in a line; a line contains aliases in increasing order. Arrange persons in descending order of the quality characteristic Q . As in input, each integer in output is of two digits, including a non-significant 0 when required. A blank line appears after the last output line of a test case. Sample Input 336 06 01 09 04 05 08 02 09 07 03 09 03 3764 242 03 08 02 05 0

Sample Output 02 06 07 01 05 09 03 04 08 02 03 06 07 01 04 05 08

70. Begin a sequence of distinct natural numbers Ni , i = 0, 1, 2,... , with the number B (= N0) ; generate numbers Ni , i = 1, 2,... , recursively and end the sequence with the last generated number E . The characteristic of numbers and the process for generation are stated below: Each number in the sequence contains an even number of decimal digits and is of the form f1d1f2d2fk...dk where d1, d2,..., dk , are k distinct digits in increasing order and each fj is a non-zero digit. For i = 0, 1, 2,... , if Ni = f1d1f2d2...fkdk then Ni+1 = F1D1F2D2...FKDK , where K k ; D1, D2,..., DK ,are distinct digits that occur in Ni and appear in increasing order in Ni+1 ; and FJ is the frequency of DJ in Ni , for J = 1, 2,..., K . For example if Ni = 102335 then Ni+1 = 1011122315 . Write a program to find for a given E , the longest sequence of numbers that ends with E and begins with the smallest B . Again consider an example; if E =1011122315 then the required sequence of numbers is 303355 103325 1011122315. Input The input may contain multiple test cases. Each test case contains only one input, viz., E . The input terminates when a line containing 0 appears as a test case. Output For each test case, print the longest sequence of numbers that ends with E and begins with the smallest B . Use space to separate two consecutive numbers in the sequence. Sample Input 1011122315 22 112213 0 Sample Output 303355 103325 1011122315 22 13 1113 3113 2123 112213

71. Crossbits are like Crosswords; instead of entering words you enter binary bits 01 in a Crossbit under certain given conditions, assuming that a solution exists. An empty Crossbit

of size N is an empty grid of size NN . Given a natural number N , consider entering N2 binary bits in an empty Crossbit, satisfying the following conditions: Each square in the grid contains either a 0-bit or a 1-bit with no 1-bit in two major diagonals.The total number of 1-bit in each row / column is exactly equal to K , K being a given natural number less than N . A 0-bit has at least another adjacent 0-bit either in the same row or in the same column. The Crossbit represents the N2 -bit binary number B formed by placing bits in the 1st , the 2nd , ... theNth row from left to right You are required to write a program that enters bits in an empty Crossbit so that the Crossbit represents the least binary number B for given N and K . As an illustration consider the case with N = 4 and K = 1 . The Crossbit shown below represents the least binary number B = 0010100000010100 of 16 bits satisfying the specified conditions. Input The input may contain multiple test cases. For each test case parameters N and K of the Crossbit are given in one line. Assume that N does not exceed 10. The input terminates with a line containing 0 as input. Output For each test case, print the Crossbit in N rows; each row contains N bits with a space between two neighbouring bits. Keep a blank line after the last output line of each test case. Sample Input 41 62 0 Sample Output 0010 1000 0001 0100 3766 - Crossbits

72. Disputes between two warring parties over possession of properties are often settled amicably with the intervention of a third party. You are required to write a program on behalf of a consultancy firm that settles disputes amicably over possession of properties between two warring parties.The dispute between two warring parties A and B, is over a set of n profit making industrial units (PMIU) thatcurrently make profits P1, P2,..., Pn . Assume that n is an even number less than 20. Each profit is a distinct integer representing rounded profit in crores of rupees. A profit identifies a PMIU and determines its valuation. For a subset of PMIU, the product of all profits from PMIU in the subset determines the total valuation of the subset. The two warring parties have agreed to accept a solution that divides the set of n PMIU into two disjoint subsets satisfying the following conditions: 1. The total number of PMIU in each subset is n/2 .

2. The total valuation of each subset is the same. 3. The subset with higher total sum of profits is allocated to A. Write a program that determines the subset of PMIU to be allocated to A, assuming that there exists a unique solution to the problem. As a simple example consider 6 PMIU with profits 2, 4, 5, 12, 15 and 18. The subset of PMIU allocated to A is {2, 12, 15}. Input The input may contain multiple test cases. For each test case there is a single input line. The line gives a set of distinct integers representing profits of PMIU. The input terminates with a line containing 0 as input. Output For each test case there is only one output line. The line prints the subset of PMIU allocated to A in ascending order of profits. Sample Input 8 12 10 15 2 4 5 12 15 18 0 Sample Output 8 15 2 12 15

73. Elimination of contestants from a live IQ contest on a TV channel is decided in phases. Initially at phase 0, N contestants, where N = 2n , n < 10 , are selected through a special online IQ contest in which a total of M (M > N) contestants participate. The contestants are identified by distinct registration numbers 1, 2,..., M . The selected contestants are ranked distinctly from 1 to N according to their performance in the online contest. They are qualified to participate in the live contest. In the pth phase, p = 1, 2,..., n, Kp contestants participate in the live contest, where Kp = 2n-p+1 . On the basis of response to questions presented during the show, Kp/2 of Kp contestants are ranked distinctly from 1 to Kp/2 . These Kp/2 contestants qualify to participate in the next phase. At the nth phase there are only two contestants and the one selected at this phase is the winner of the contest.You are required to write a program that identifies the winner of the contest, given the following information: INFO_1: Registration numbers of N contestants who are selected through the online IQ contest, in order of the rank in the online IQ contest, and INFO_2: A total of N - 1 qualified contestants in different phases; K2 in phase 1, K3 in phase 2, ... ,and Kn+1 in phase n . Qualified contestants of different phases appear in order of phases, i.e., phase 1,phase 2, ... , phase n . Further, qualified contestants in a phase, say phase p , appear in the order of therank in the phase, i.e., the rank in phase p .

A qualified contestant of a phase, say phase p , is identified by his/her rank in the previous phase, i.e., in phase p - 1 . Input Input may contain multiple test cases. For each case there are two input lines. The first line gives N integers representing INFO_1 while the second line gives N - 1 integers representing INFO_2. In each input line integers are separated by space. The input terminates with a line containing 0 as input. Output For each test case there is only one output line. The line prints the registration number of the winner of the contest. Sample Input 23 18 6 20 422 29 57 4 33 5 12 16 18 7153211 0 3768

74. Friends are as friends should be. Friends believe each other, help each other and above all share joys, sorrows and problems. Friendship is mutual.A college is on vacation. Classmates of a class are in their respective homes. It is a common knowledge to all classmates, who is a friend of whom. Friends among classmates are in direct contact through SMS. A classmate may send SMS to certain specified classmates through friends in minimum time. Assume that it takes exactly one unit of time to send an SMS from a sender to a receiver. When a classmate initiates transmitting an SMS at time 0 to a friend, the friend receives the SMS at time 1. At time 1 both the initiator and the friend may send SMS to two different receivers simultaneously. Consider all senders at time t and all receivers at time (t + 1), t = 1, 2 , etc. Senders are classmates who have either received SMS at time t or sent the last SMS at time (t - 1) . Receivers are classmates who have not received SMS as yet and are friends of one or more senders. Who sends SMS to whom and when? The initiator decides in advance senders, receivers and times so that the SMS reaches specified classmates in minimum time. This information is transmitted to each receiver along with the SMS. Write a program that finds the minimum time required for an SMS from a given initiator to reach three specified classmates through friends. Assume that the total number of classmates in a class does not exceed 50 and the roll number identifies a classmate. Input The input may contain multiple test cases. For each test case there are two input lines. The first line identifies friends among classmates. It gives an even number of integers representing roll numbers. Each pair of integers in the line, one appearing in an odd numbered position and the other appearing in the next even numbered position,

represents roll numbers of a pair of friends among classmates.The second line gives four integers. The first integer is the roll number of the initiator while the other integers are the roll numbers of three specified classmates. Integers in an input line are separated by space. The input terminates with a line containing 0 as input. Output For each test case, print output in a single line. The line gives the minimum time required for the SMS from the initiator to reach specified classmates through friends. Sample Input 3224254515 4123 3224254515 2345 134672413676325185 1678 3769

75. You are invited to be a part of the team that is developing yet another DBMS

(Data Base Management System). You will be responsible for the Lock Manager. Locks control concurrent access to data items by multiple transactions. Your DBMS is simple and uses only Shared (S) and Exclusive (X) mode locks. Each lock request contains a lock mode (S or X), a transaction identifier and a data item identifier. Multiple locks can be granted to the same data item as long as none of them conflict. Two locks for the same data item conflict if: they belong to different transactions, and at least one of them is exclusive (X) mode lock. At the earliest stages of development you are asked to write very simple lock manager that processes lock requests. The lock is granted if it does not conflict with previously granted locks for this data item. Your task is simple: locks, once granted, are never released or changed in any way. If lock request is denied due to conflict with some previously granted lock, then transaction making this request is blocked and all further requests from this transaction are ignored. Input The first line of the input consists of an integer indicating the number of test cases in the input. Then there is a blank line and the test cases separated by a

blank line.Each test case consists of a number of lock requests, each request on a different line. Requests have the following format:
MODE TRID ITEM

Where MODE is a single capital letter S or X denoting requested lock mode. TRID and ITEM are transaction identifier and data item identifier correspondingly. Both TRID and ITEM are integers, both are greater than zero, and both consist of at most 9 decimal digits. There are at least one and at most 10000 requests in each test case. The last request is followed by a line consisting of a single character '#'. Output Your program shall sequentially process all requests from each test case. For each request you should write one line that contains the response to the request. The following responses are allowed: GRANTED - the lock request does not conflict with any previously granted locks and is granted. DENIED - the lock request conflicts with some previously granted lock and is denied, thus blocking the requesting transaction. IGNORED - the transaction was blocked on some request before this one. Responses shall appear in all capital letters exactly as shown above. Print a blank line between data sets. Sample input
1 S S X S S X S S S X X 1 1 2 2 10 1 6 123456789 3 3 2 2 5 6 3 1 3 2 987654321 123456789 1 4

S S S X S #

6 3 2 4 2

6 5 4 5 51

Output for the sample input


GRANTED GRANTED DENIED GRANTED GRANTED GRANTED GRANTED GRANTED DENIED DENIED GRANTED GRANTED IGNORED DENIED GRANTED IGNORED

76. Mr. Smith received a loan for Q dollars. He plans to pay off this loan in K years

at an interest rate of P percent per year. That means that, after each year, Mr. Smith's debt grows by P*Q'/100 dollars (Q' being the debt at the beginning of that year) and his annual payment is deducted from his debt. For the first year, Mr. Smith wants to pay minimal amount that will allow him to pay off the loan within exactly K years. For each subsequent year, he is willing to pay either the same amount as the previous year or one cent less than the previous year's payment. He wants the loan to be completely paid off without overpayment of even a single cent by the end of the Kth year. The bank performs all transactions with a precision of one cent, and calculates interest due at the end of each year. Whenever interest is calculated, the result is immediately rounded to the nearest cent, with 0.5 cents rounded up. Input The first line of the input contains an integer indicating the number of test cases in the input. Then there will be a blank line, and the test cases separated by a blank line. Each test case consists of a single line with three

numbers Q,P and K, separated by spaces. Q is a real number (10 Q 1000000) given with no more than two digits to the right of the decimal point. This value represents the amount of the loan in dollars. One one-hundredth of a dollar is a cent. P and K are integers (0 P 100, 1 K 100). Output Write to the output file a schedule of payments for Mr. Smith. You should write the amount of each payment and number of years that payment should be made, thus effectively grouping equal payments. Each group of equal payments must be written on separate line, with no blank lines between them. The output format for each group of payments is:
$X for Y year(s)

where X is payment amount in dollars printed with exactly two digits after decimal point. Y is a number of years for which this payment should be made. The dollar value given on each line must be one cent less than the dollar value printed above it. If there are multiple correct payment schedules, you can output any one of them, but the first payment should be the minimal possible one. If no solution can be found for the given input, then the output file shall contain only the word "Impossible". Print a blank line between test cases. Sample Input
3 100 100 100 20 0 10 939850.83 85 35

Sample Output
Impossible $2.00 for 10 year(s)

$798873.22 $798873.21 $798873.20 $798873.19 $798873.18 $798873.17 $798873.16 $798873.15 $798873.14 $798873.13 $798873.12 $798873.11 $798873.10 $798873.09 $798873.08 $798873.07 $798873.06 $798873.05

for for for for for for for for for for for for for for for for for for

1 1 1 1 1 4 1 2 1 3 1 4 2 7 2 1 1 1

year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s) year(s)

77. Consider an arbitrary sequence of integers. One can place + or - operators between integers in the sequence, thus deriving different arithmetical expressions that evaluate to different values. Let us, for example, take the sequence: 17, 5, 21, 15. There are eight possible expressions:
17 + 5 + -21 + 15 = 16 17 + 5 + -21 - 15 = -14 17 + 5 - -21 + 15 = 58 17 + 5 - -21 - 15 = 28 17 - 5 + -21 + 15 = 6 17 - 5 + -21 - 15 = -24 17 - 5 - -21 + 15 = 48 17 - 5 - -21 - 15 = 18

We call the sequence of integers divisible byK if + or - operators can be placed between integers in the sequence in such way that resulting value is divisible by K. In the above example, the sequence is divisible by 7 (17+5+-21-15=-14) but is not divisible by 5.You are to write a program that will determine divisibility of sequence of integers.

Input The first line of the input file contains a integer M indicating the number of cases to be analyzed. Then M couples of lines follow. For each one of this couples, the first line contains two integers, N and K(1 <= N <= 10000, 2 <= K <= 100) separated by a space. The second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it's absolute value. Output For each case in the input file, write to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not. Sample input
2 4 7 17 5 -21 15 4 5 17 5 -21 15

Sample Output
Divisible Not divisible

78. It is known that Sheffer stroke function (NOT-AND) can be used to construct

any Boolean function. The truth table for this function is given below:
Truth table for Sheffer stroke function x 0 0 1 1 y 0 1 0 1 x|y 1 1 1 0

Consider the problem of adding two binary numbers A and B, each containing N bits. The individual bits of A and B are numbered from 0 (the least significant) to N-1 (the most significant). The sum of A and B can always be represented by N+1 bits. Let's call most significant bit of the sum (bit number N) theoverflow bit. Your task is to construct a logical expression using the Sheffer stroke function that computes the value of the overflow bit for arbitrary values of A and B. Your expression shall be constructed according to the following rules: 1. 2. 3. is an expression that denotes value of ith bit of number A. th Bi is an expression that denotes value of i bit of number B. (x|y) is an expression that denotes the result of Sheffer stroke function for xand y, where x and y are expressions.
Ai

When writing the index, i, for bits in A and B, the index shall be written as a decimal number without leading zeros. For example, bit number 12 of A must be written as A12. The expression should be completely parenthesized (according to the 3rd rule). No blanks are allowed inside the expression. Input The first line of the input contains an integer indicating the number of test cases in the input. After that there is a blank line and the test cases separated by a blank line. Each test case consists of a single integer N (1 N 100) on a line by itself. Output Write to the output file an expression for calculating overflow bit of the addition of twoN-bit numbers A and B according to the rules given in the problem statement. Print a blank line between test cases. Note: The stroke symbol ( | ) is an ASCII character with code 124 (decimal). The output file size shall not exceed 50*Nbytes. Sample input
1

Sample output for the sample input


((A1|B1)|(((A0|B0)|(A0|B0))|((A1|A1)|(B1|B1))))

79. The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very

poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can't reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system. Flatopian towns are numbered from 1 to Nand town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways. The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length. Input The first line of the input consists of an integer indicating the number of test cases in the input. Then there's a blank line and the datasets separated by a blank line. Each test case consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built. The first line of the test case contains a single integer N (1 N 750), representing the number of towns. The next N lines each contain two integers, xi and yi separated by a space. These values give the coordinates

of ithtown (for i from 1 to N). Coordinates will have an absolute value no greater than 10000. Every town has a unique location. The next line contains a single integer M(0 M 1000), representing the number of existing highways. The next M lines each contain a pair of integers separated by a space. These two integers give a pair of town numbers which are already connected by a highway. Each pair of towns is connected by at most one highway. Output Write to the output file a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space. If no new highways need to be built (all towns are already connected), then the output file should contain a line with the sentence "No new highways need". Print a blank line between test cases. Sample input
1 9 1 0 3 4 5 0 5 1 5 3 1 9 1 5 0 2 5 1 4 2 2 3 3 7 2

Sample output for the sample input


1 3 4 5 8 6 7 9 7 3

80. There are three computers connected by a network. One of them is a server and

the other two are clients. The server has some files, each with a different name. The full name of each file consists of two parts, a name and an extension. Both clients know the full names of all of the files stored on the server. From among its files, the server chooses a single file and sends the name part of that file's full name to one of the clients and the extension part of the full name to the other client. The clients then begin communicating in an effort to determine which file was selected by the server (they want to learn the file's full name). However, the clients have to communicate in a very restricted manner. Clients take turns sending messages to each other, but they can only say when they don't know the full name of the file. If one client does not know the full name of the chosen file, that client may send a message saying "I don't know the full file name" to the other client. The two clients alternate, sending only this message back and forth. This continues until either one of the clients knows the full file name or they decide to quit. The client that received the name part of the full file name always waits for the other client to send the first message. Pretend that you know all the full file names that reside on the server (both the name and the extension part) and you are listening to the conversation between the clients. Based on this conversation, you should determine the set of files that might have been chosen by the server. Files in this set are called candidate files. Input The first line is the number of test cases, followed by a blank line. The first line of each test case in the input file contains two integers N and M, separated by a space. N (1 <= N <= 1000) is the number of files of the server, and M (1 <= M <= 100) is the number of messages exchanged between the clients in their effort to determine the full file name. Each of the next N lines, in each test case contain one full file name. Full file names are given in a manner similar to MS-DOS 8.3 format. Each full file name is represented in name.extension form, where both the name and the extension consist of only capital, alphabetic characters and decimal digits. The name part will have at least one character and at most eight. The extension part will have at most three characters and may be empty. If extension is empty then separating dot may be omitted. Each full file name appears in each test case no more than once.

Each test case will be separated by a single line. Output Write on the first line of the output for each test case, the number of candidate files based on the given set of files and the number of messages exchanged between the clients. Write zero if there are no candidate files. On the following lines for each test case, write the full names of all candidate files. Each of these names should be written on a separate line. They should appear in the same order and with exactly the same spelling as in the input file. That means that if the separating dot was omitted in the input for a particular file then it should also be omitted for this file in the output and vice versa. No file may be listed more than once. Print a blank line between the outputs for two consecutive test cases. Sample input
1 19 2 LICENCE.TMP WIN32.LOG FILEID. PSTOTEXT.TXT GSVIEW32.EXE GSVIEW32.ICO GSVIEWDE.HLP LICENCE GSVIEWEN.HLP GSVW32DE.DLL FILEID.TMP GSVW32EN.DLL PSTOTXT3.DLL PSTOTXT3.EXE GSV16SPL.EXE GVWGS32.EXE ZLIB32.DLL PRINTER.INI README.TXT

Sample Output
6 LICENCE.TMP FILEID. LICENCE FILEID.TMP PSTOTXT3.DLL

PSTOTXT3.EXE

81. The Department of Recreation has decided that it must be more profitable, and it

wants to sell advertising space along a popular jogging path at a local park. They have built a number of billboards (special signs for advertisements) along the path and have decided to sell advertising space on these billboards. Billboards are situated evenly along the jogging path, and they are given consecutive integer numbers corresponding to their order along the path. At most one advertisement can be placed on each billboard. A particular client wishes to purchase advertising space on these billboards but needs guarantees that every jogger will see it's advertisement at least K times while running along the path. However, different joggers run along different parts of the path. Interviews with joggers revealed that each of them has chosen a section of the path which he/she likes to run along every day. Since advertisers care only about billboards seen by joggers, each jogger's personal path can be identified by the sequence of billboards viewed during a run. Taking into account that billboards are numbered consecutively, it is sufficient to record the first and the last billboard numbers seen by each jogger. Unfortunately, interviews with joggers also showed that some joggers don't run far enough to see K billboards. Some of them are in such bad shape that they get to see only one billboard (here, the first and last billboard numbers for their path will be identical). Since out-of-shape joggers won't get to see Kbillboards, the client requires that they see an advertisement on every billboard along their section of the path. Although this is not as good as them seeing K advertisements, this is the best that can be done and it's enough to satisfy the client. In order to reduce advertising costs, the client hires you to figure out how to minimize the number of billboards they need to pay for and, at the same time, satisfy stated requirements. Input The first line of the input consist of an integer indicating the number of test cases in theinput. Then there's a blank line and the test cases separated by a blank line.

The first line of each test case contains two integers K and N (1 K, N 1000) separated by a space. K is the minimal number of advertisements that every jogger must see, and N is the total number of joggers. The following N lines describe the path of each jogger. Each line contains two integers Ai andBi (both numbers are not greater than 10000 by absolute value). Ai represents the first billboard number seen by jogger number i andBi gives the last billboard number seen by that jogger. During a run, jogger i will see billboards Ai, Bi and all billboards between them. Output On the first line of the output fof each test case, write a single integer M. This number gives the minimal number of advertisements that should be placed on billboards in order to fulfill the client's requirements. Then write Mlines with one number on each line. These numbers give (in ascending order) the billboard numbers on which the client's advertisements should be placed. Print a blank line between test cases. Sample input
1 5 10 1 10 20 27 0 -3 15 15 8 2 7 30 -1 -10 27 20 2 9 14 21

Sample output for the sample input


19 -5 -4 -3 -2 -1 0 4 5 6 7 8

15 18 19 20 21 25 26 27

82. Company ACIDIC manufactures acid. The acid is filled into containers and sent out to different places. Sometimes, the containers start leaking. To handle such situations, the company has a room with several container holders. These holders are arranged in a rectangle grid. Each of these can hold one leaky container and absorb the acid leakage. After all the acid has leaked out, the containers are taken out and the leak point(s) are fixed. One day, the leaky containers were put in some of the holders. After a while, some more leaky containers were detected and brought to the room. The supervisor handling this then realized that all the containers that are present in the room are leaking very heavily. So heavily that they have corroded their holders and in a short time they would also corrode all the holders in the room in the directions of the leak.The containers are leaking either in the North-South direction or in the East-West direction. (The figure above shows a room with a 4-by-6 grid of holders having four leaky containers. The dashed arrows represent the direction of leakage.) The supervisor tried to remove containers from their holders but could not as they were stuck to the holders. However, he could rotate the containers so that the direction of leakage could be changed from North-South to East-West or vice-versa. The supervisor suspects that the current lot of leaky containers may also start to leak heavily. Help the supervisor find the rotations of existing containers and placement of current lot of containers so that the number of corroded holders is minimized.

Input
There are several test cases. The first line of the input contains the number of test cases T. For each test case, the first line has four numbers R, C, N and M. Numbers R and C (between 10 and 100) give the number of rows and columns in the grid. Number N (between 1 and 20) gives the number of leaky containers in the room and number M (between 1 and 20) gives the number of leaky containers in the current lot. Each of the next N lines gives the placement and the leakage direction of an existing container. These are given as three numbers a, b, and c where a (between 1 and R) is the row number (counting from top), b (between 1 and C) is the column number (counting from left), and c is 1 if the leakage direction is North-South, 0 otherwise.

Output
For each test case, the output should be a number giving the smallest number of holders that will get corroded after rotating the existing containers and placing the containers in the current lot (assuming the all the current lot containers will also leak heavily). The output for different test cases should be on different lines.

Sample Input
2 4 6 4 4 1 2 0 2 4 0 3 2 1 3 5 1 50 50 5 10 1 35 1 17 44 0 17 46 1 42 35 1 42 46 0

Sample Output
12 148

83. A cooperative society has purchased some land for distribution amongst its members. The land is divided into plots so that every member can get a plot. It is planned to mark each plot by a two meter high boundary wall. The boundary of each plot is shaped like a polygon (not necessarily a convex one). (The figure below shows a land with five plots.) It is divided into line segments such that any two line segments either intersect at an end point or do not intersect at all (there may be co-linear segments present). A builder has been hired to construct the boundary walls. He has put different groups of workers to work on different segments of the boundary wall (a segment of boundary wall corresponds to a line segment in the boundary of a plot). All the groups, at the end of the day, submit their report to the contractor indicating whether their work is finished or not. Write a program to help identify the builder the number of plots for which the work has been completed.

Input
The first line of the input gives the number of test cases T. For each test case, the first line contains an integer N (between 3 and 50) giving the number of line segments in the land. The j-th of the next N lines contains five integers a, b, c, d, and e where (a, b) and (c, d ) give the coordinates of the corner point of the j-th line segment and the number e is 1 if that boundary wall segment is complete, 0 otherwise.

Output
For each test case, there is one line in the output giving the number of plots on which work is completed.

Sample Input
2 5 0 0 0 1 0 7 0 0 2 2 1 1 0 1 2 0 0 1 0 0 0 0 0 2 2 2 1 0 1 1 1 1 2 0 2 1 0 1 1 1 0 1 1 1 0 1 2 2 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1

Sample Output
84. Error correction is extremely useful in recovering from corrupted data. The abstract setting for this problem is: given a set of n data elements such that at least t of the data elements are uncorrupted, recover the complete uncorrupted data from it. To be able to do such a correction, data elements need to be of special form. Such forms are called Error-correcting codes. An error-correcting code that is widely used is as follows: the data elements are evaluations of a univariate polynomial of degree d modulo a prime number p. The error-correction algorithm for this code was very complex until Madhu Sudan discovered a nice way of doing this. His algorithm is: given a set of n points y1,..., yn (each value is between 0 and p - 1, and also n < p) with at least t of the y's correct (this

means that for the correct yj, yj = P(j) for some unknown degree d polynomial modulo p) do the following: a. Construct a non-zero polynomial in two variables Q(x, y) with the degree of y being e and the degree of x being f and (e + 1)*(f + 1) > n and e*d + f < t for which Q(j, yj) = 0 for every j between 1 and n. The exact values of e and f are determined using t, d, and n. b. Factor the polynomial Q into irreducible factors. Consider all the factors of the form (y - g(x)) such that degree of g is d and identify one for which yj =g(j) for at least t values. c. This identified polynomial, g, is the desired one. Once the polynomial is identified, all the correct values of y can be recovered by computing g(j) for every j. Madhu Sudan has written programs for factoring the two variable polynomial and for identifying the right polynomial as well as computed the right values of e and f. He now just needs a program that constructs the two variable polynomial Q. Please help him in writing this program.

Input
The number of test cases T is written in the first line of the input. For each test case, the first line contains the value of n, p, e, and f (all these are between 1 and 100 satisfying the constraints mentioned above; in particular, p is always a prime number) in that order. The j-th of the next n lines contains the value yj.

Output
For each test case, output all the coefficients of the polynomial Q in the following order: first output all the coefficients of the terms in which the degree of y is zero and order these coefficients by increasing degree of x; then output all the coefficients of the terms in which degree of y is one ordering these in the same way as before, and so on. Each coefficient must be on a separate line. If there are more than one solutions, output any one. The output of different test cases must be separated by a blank line.

Sample In
6 4 5 4 11 1 2 2 3 0 0

Sample Output
0 4 3 1 1 4 1 2 6 0

85. One day, looking at old documents inherited from his grandfather, Ramesh discovers a map. Reading the accompanying document, he realizes that the map is of a complex maze of chambers and passages inside a mountain. Chambers in this maze have doors opening to passages leading to other chambers. All the doors have one peculiarity: they have handles only on one side, and so can be opened either from the chamber or from the passage but not both. The passages leading from

any chamber have been designed in such a way that either there is only one passage leading out or there is a passage such that upon following it one can never come back to the chamber. Also, there is at most one passage between any two chambers. On the ceiling of each chamber, a number is written. There are two special chambers: the entry chamber and the exit chamber. The entry chamber can be entered via a door from outside the mountain and the exit chamber has a door that leads to a secret chamber. The exit door opens only upon reciting a magic sequence of numbers. It is given that this sequence is the only sequence of numbers satisfying the following properties: . The sequence can be constructed by noting the numbers written in chambers, in that order, on a path from entry chamber to exit chamber The numbers in the sequence are all distinct. If any chamber has a number from this sequence written, then there is a path from the chamber to the exit chamber such that all the chambers in this path contain numbers only from this sequence. Design an algorithm to help Ramesh reach the secret chamber.

Input
The first line of the input consists of an integer T giving the number of test cases to follow. The first line of each test case contains two integers N (between 1 and 100) and P (between 1 and 1000)giving the number of chambers and the number of passages in the maze respectively. The next line contains N numbers: the j-th number is written in the j-th chamber. Each of the next P lines contain four numbers a, b, c,d with a, b between 1 and N and c, d having binary value, giving that there is a passage between chamber number a and chamber number b such that the door to the passage from chamber a opens from inside the chamber if c = 1 and the door to the passage from chamber b opens from inside the chamber if d = 1. The last line of the test case contains two numbers s and t with s being the entry chamber number and t being the exit chamber number.

Output
For each test case in the input, there is one output line that contains the magic sequence with numbers separated by blanks.

Sample Input
2 6 6 9 10 11 12 13 14 1 2 1 0 2 3 1 0 3 4 1 0 4 5 1 0 4 6 1 0 4 2 1 0 1 5 10 13 22 81 84 84 72 60 63 62 99 54 1 2 1 0 1 4 1 1 2 4 1 0 2 5 1 0 5 3 0 1 6 3 0 1 4 7 1 0 8 4 0 1 5 2 1 0 5 8 1 0 9 5 0 1 9 6 0 1 10 6 0 1

1 9

Sample Output
9 10 11 12 13 22 81 72 99

86. The director of Hind Circus has decided to add a new performance, the monkey dance, to his show. The monkey dance is danced simultaneously by N monkeys. There are N circles drawn on the ground. In the beginning, each monkey sits on a different circle. There are N arrows drawn from circle to circle in such a way that in each circle, exactly one arrow starts and exactly one ends. No arrow can both begin and end at the same circle. When the show begins, at each whistle of the ringmaster, all the monkeys simultaneously jump from their respective circles to other circles following the arrows from their respective current circles. This is one step of the dance. The dance ends when all the monkeys have returned to the circles where they initially started. The director wishes the dance to last as many steps as possible. This can be achieved by drawing the arrows intelligently. Given N, you have to write a program to determine the maximum possible number of steps such that there is a way of drawing the arrows to make the dance last these many steps.

Input
The input may have multiple cases. Each case consists of just the value of N (N 40) on a separate line. The input ends with a `0' for the value of N.

Output
For each case, simply output the maximum possible number of steps. Each output should be on a separate line.

Sample Input
5 8 0

Sample Output
6 15

87. A skier wants to ski down from the top of a mountain to its base. There are several possible routes, using different slopes enroute, and passing through some flat areas. The effort expended in skiing down a slope depends upon the length of the slope and the speed of skiing. For each slope, there is a maximum advisable speed. The skier wants to use a route that minimizes the average effort spent per unit distance traveled (i.e., the total effort expended divided by the total distance traveled). You are given the map of the mountain slopes. That is, the flat areas and the slopes connecting these areas are given. Note that on a slope, one can only ski downwards. For each slope, you are also given the length of the slope and the maximum advisable speed for it. The effort expanded in skiing down a particular slope is given by the following formula. e = d*(70 - s) if s 60, and e = d*(s - 50) if s > 60 where e is the effort required, d is the distance traveled, and s is the speed of travel. You have to determine the minimum average effort per unit distance that the skier has to expend in order to reach the mountain base, while staying within the maximum advisable speed at every slope.

Input
The input may have multiple test cases. The first line of input gives the number of test cases T. For each test case, the first line of input gives the number of flats, N (N 100), and the number of slopes, R (R 10000), connecting them respectively. The flats are assumed to be numbered from 1 to N. The flats at the top and the base of the mountain are assumed to be numbered 1 and N

respectively. Each of the next R lines describes a slope by giving: the numbers of the flats at the top and the bottom of the slope, the maximum advisable speed for the slope, and the length of the slope respectively.

Output
For each test case, output a single number (to an accuracy of 2 decimal places) that gives the minimum average effort per unit distance that needs to be expended to ski down from the mountain top to the base. The output for each test case should be on a separate line.

Sample Input
2 4 1 1 1 1 2 3 3 1 1 2 5 4 4 2 3 4 4 3 2 3 3 30 60 50 40 60 20 60 50 50 50 1 3 50 40 40 20 20 30

Sample Output
14.44 30.00

88. A spaceship is to be launched from the Earth to visit a number of planets. The order of visiting the planets is fixed. The spaceship can travel from one planet to another via normal space or via hyperspace. Hyperspace travel reduces the traveled distance substantially, however, the fuel consumption during the hyperspace travel is much more. In fact, if the spaceship travels d light years thorough the hyperspace, then the fuel consumed is d4 units! For d light years traveled through normal space, the fuel consumed is just d units. Also, between two planets, the spaceship can either travel via hyperspace or normal space but not both. Design an algorithm that determines a way of traveling that minimizes the fuel consumption.

Input
The first line of the input file contains a number T giving the number of test cases to follow. The first line of each test case contains an integer N (between 1 and 50) giving the number of planets to be visited. The j-th of the next N lines correspond to the j-th planet to be visited and contains two integers hd and nd denoting respectively the hyperspace and normal space distance between the (j - 1)-th planet and j-th planet (the 0-th planet is taken to be the Earth). The number hd is between 1 and 10 light years and the number nd is between 1 light year and 10 million light years.

Output
For each test case in the input, output a number giving the minimum units of fuel required to visit all the planets. Each test case output must be on a separate line.

Sample Input
2 3 3 2 4 5 1 2 7 4 1000 5000 8000 10000 3547 36782 2178

9 67428

Sample Output
2296 52507

89. A battalion of tanks is to be sent to a border post from the base. There are no obstructions between the base and the border post and so the tanks can travel in any direction. However, the terrain between the base and the border post is of two kind: first comes the muddy terrain and then the desert. The maximum velocity of a tank in each of these terrains is different. It is assumed that a straight line separates the two terrains. Design an algorithm that finds out the fastest route to the border post.

Input
There are several test cases. The first line of the input contains the number of test cases T. For each test case, the first line has two numbers u and v with u being the maximum velocity (in kilometers per hour) of a tank in the desert and v the maximum velocity in the muddy terrain. The next line contains the coordinates of the border post assuming the dividing line between the terrains to be the x-axis (the y-coordinate of the border post is always positive). The third line contains the coordinates of the base camp(the y-coordinate of the base camp is always negative). The unit of the coordinates is kilometers.

Output
For each test case, there is one output line containing two numbers: the first number denotes the time taken in seconds (rounded off to the closest second) by a tank to reach the border post by the fastest route. The second number denotes the x-coordinate (in kilometers, with an accuracy of three decimal digits) of the point where the tank crosses over to the desert.

Sample Input
2 1 1 5 3 5 -2 3 5 20 10 8 -9

Sample Output
18000 5.000 21590 15.688

90. Modern writers do not use pens to write books. They enter the text directly on to the home PCs using MSWord and edit the text when necessary. After entering the text for a new book, a famous novelist desires to have a major rearrangement of the text he has prepared. He has identified passages in the text and numbered these passages. However the passages are not in proper sequence. He wants to use the minimum number of cut and paste operations of MS Word to edit the text and put the passages in proper order. He may do the operation either with one passage or with a number of passages occurring in a sequence. He needs a program for this purpose. The following example illustrates his problem. In order to edit the text containing 6 passages in the sequence P2, P4, P1, P5, P3, P6 so that the passages appear in the text in the proper sequence viz., P1, P2, P3, P4, P5,P6 he needs at least 2 cut and paste operations:
c u t P 1 a n d p a s1t.e before P2 to get P1, P2, P4, P5, P3, P6 and 2c.u t P3 and paste after P2 to get P1, P2, P3, P4, P5, P6.

Can you write a program for him?

Input

The input may contain multiple test cases. For each test case, the first line contains two integers, the case number c and the total number n of passages.For simplicity, passages are represented by integers 1, 2,..., n. The input sequence of passages is given in n lines, each line containing one integer in the order in which the passages appear in the text before editing.The entire input set terminates with an input `0' for c.

Output
For each test case in the input, print the test case number c and the total number k of cut and paste operations needed for the rearrangement of passages. Print the given sequence in one line. In the next k lines print successive changes in the sequence of passages due to application of k cut and paste operations. Print a blank line between outputs of two test cases.

Sample Input
1 6 2 4 1 5 3 6 2 15 12 6 7 2 3 4 9 10 11 1 5 8 13 14 15 0

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

1 5 8 4 5 8 6 7 8 10 11 11 12

13 13 13 13 13

14 14 14 14 14

15 15 15 15 15

91. Mr. Paisawalla died at the age of 79. He was a rich man. He left behind lots of immovable property. Before his death, he made a will for disposition of his property to his wife, three sons and a daughter. The directions in the will were as follows: 1.The property should be disposed of impartially and equally to his wife, three sons and the daughter according to current valuation of property and practical limitations. 2.As far as practicable equality in shares should be maintained. However, if complete equality is not feasible, then the largest difference between shares of any two members should be the least.

In such acase the disposal should be in decreasing order of shares to wife, son1, son2, son3 and the daughter. 3. The impartiality in valuation is to be ensured by an impartial committee for valuation. 4. The equality and impartiality in disposition are to be ensured by entrusting the job to a software professional who should write a program for taking computer-based decisions. As an illustration let the property of late Mr. Paisawalla be as indicated in the table below: The disposition should be as follows: Are you prepared to write a computer program for disposition of the property of late Mr. Paisawalla? The program should be able to provide solutions to other similar cases. Assume that the total number of receivers to whom the property is to be distributed is m and the receivers are represented by integers 1, 2,..., m. In case equality in disposition is not feasible the disposition should be such that share of property decreases as the number representing a receiver increases.

Input
The input may contain multiple test cases for testing the program. For each test case, the first line contains three integers, the case number c, the total number n of property and the total number m of receivers to whom the property is to be distributed. For simplicity, properties are identified by integers 1, 2,..., n. The valuations of property are given in n lines,the i-th line gives the valuation of the i-th property. The entire input set terminates with an input `0' for c.

Output
For each test case in the input, print the test case number c and the difference between the largest and the smallest allocation of shares. Write shares of the property allocated to m receivers in the next m lines. The i-th line contains the total valuation of shares received by the i-th receiver, together with the list of property in increasing order of the number representing the property, as shown in the sample output.

Sample Input
1 9 5 49 78 83 35 10 109 95 23 62 2 11 4 83 142 75 93 43 5271812962120

Sample Output
1 8 113 111 109 106 105 2 1 173 172 172 172 2 1 6 3 5 3 5 1 2 4 9 8 7 4 6 9 7 10 8 11

92. A community named DAMPU lives in the twenty first century. However it still follows some of its old outdated traditional community customs very strictly, even though its members are used to modern way of life and use modern gadgets including computers for its activities and recreations. The DAMPU community is closed in the sense that marriages take place according to the old custom between a male and a female member of the community. A member of the community is not permitted to marry outside the community. Further, members of the community are monogamous. Each unmarried living member having a specified marriageable age is eligible for marriage. An eligible member of the community can marry another eligible member of opposite sex if and only if, at least one of them is separated from the nearest common ancestor by at least k generations, k being an integer specified by the community council from time to time. The integer k is called the generation gap. For example if k = 2 then the nearest common ancestor should be either grand parents of at least one of the two members who wish to marry or ancestors of grand parents. It may be noted that the members who are already married may or may not have a generation gap of k generations because a different criterion was possibly applicable at the time when they were married. The DAMPU community wants to develop a computer program for computer based match making so that a member eligible for marriage may easily get a list of eligible members of the opposite sex with whom there is a possibility of marriage. It is known that the DAMPU community maintains a register for births, deaths and marriages and the records are available for every member of the community. Can you help the DAMPU community by writing a program for the purpose stated above?

Input
The input may contain multiple test cases. For each test case, the first line contains three integers n, N and k. The integer n is the case number, while N( <5000) is the total number of members of the community for whom data are given and k (k 100) is the specification fixed by the community council for the generation gap to be used for match making. Each of the next N lines contains relevant data (viz., Sex, Father, Mother) on members of the community selected for testing the program. The i-th line gives data for the i-th member. The members of the community for whom data are given are identified by integers 1, 2,..., N. These members include all living members who are eligible for marriage and also some ancestors of eligible members so that the eligibility for match making can be verified. Integers 1 and 0 are used to denote the sex of a member: `1', if male and `0', if female. A parent of a member is denoted by the integer `0' if the generation gap between the parent and every eligible member, other than his/her descendents, is known to be k or more. The entire input set terminates with an input `0 0 0' for n, N and k.

Output
For each test case in the input, first print in one line, the test case number n and the total number m of possible matches. Print a line for each possible match in the form: i j where i is a male member and j is a female member eligible for marriage. The list of matches should be printed in lexicographic order of i and j. Keep a blank line before printing the output for the next test case, as shown in the sample output.

Sample Input
1 1 1 0 1 0 1 0 1 9 0 0 2 1 2 1 2 6 2 0 0 0 5 0 5 0 3

0 2 1 1 1 0 0 0 0 1 0 1 1 1 0 0 1 0 1 0 0

1 5 18 3 0 0 0 0 1 6 0 0 3 4 0 0 2 14 12 13 15 7 15 7 3 4 2 14 3 4 0 0 12 13 12 13 15 7 15 7 0 0

Sample Output
1 3 4 7 8 7 8 9 2 4 10 5 11 9 11 18 17 5

93. There is a search around the world for the most wanted man (MWM) in the history of mankind. He is believed to have an extraordinary quality, either superior or inferior, compared to a normal person. He is likely to be present any where in the world. If he is spotted precisely then he may be captured without much difficulty.However the problem is in spotting him because a number of look-alikes are known to exist at different parts of the world.Apart from conventional resources, modern satellite communication and surveillance systems that can precisely identify, measure, record and monitor the physical, social, cultural and behavioral characteristics of a person, are available for collecting data on the MWM. In addition, the services of competent professionals in different disciplines are available to analyze and interpret data collected from all sources. Professional Psychologists and Statisticians admit that it is difficult for them to distinguish precisely between two persons using physical and behavioral data. However, by analyzing and interpreting group data, they claim that they can differentiate precisely between a group of normal persons and a similar group of same size that includes a person of extraordinary quality even if it is not known in advance whether the extraordinary quality is superior or inferior to that of a normal person. In such a case for a reliable comparison it is necessary that the number of persons in each group is 3 or more. In other words, let A, B be two groups of equal number of persons, the number being 3 or more. An unidentified person x having an extraordinary quality classified either superior or inferior, may or may not be present in any of the groups. It is possible to perform a special compare operation on A, B and state precisely by data analysis and interpretation, one of the following: (a)A=B indicating x is neither in A nor in B, (b)A>B indicating either x is in A and he is superior or x is in B and he is inferior, (c)A<B indicating either x is in A and he is inferior or x is in B and he is superior. The outcome of the special compare operation may be denoted by E, H and L representing the cases (a), (b)and (c) respectively.Since collection, analysis and interpretation of data are

considered costly and the total number n of look-alikes including the MWM is small, 8 n 12, it is decided that only three special compare operations on selected groups could be performed successively to spot the MWM and determine his qualitative characteristic. However it is required to select groups Ai, Bi, i = 1, 2, 3, before each special compare operation. The groups may depend on the outcome of the previous special compare operations. Write a program that selects the groups to be compared by the professionals in three stages. For each stage, you may assume that the outcomes of special compare operations are known for all previous stages. After selection of groups the program should spot the MWM when successive outcomes of special compare operations are known.

Input
The input may contain multiple test cases. The data for a test case are given in a single line. The line contains two integers, the case number c and the total number n of look-alikes, 8 n 12. It also contains a string S of three letters s1, s2, s3 representing the successive outcomes of three special compare operations to be used by your program to form the groups for comparison and to spot the MWM. The look-alikes, including the MWM w, are identified by integers 1, 2,..., n and each of the outcomes s1, s2, s3 of the special compare operations is represented by the letters `E', `H' or `L'. The i-th letter si in the string S represents the outcome of the i-th special compare operation, i = 1, 2, 3. The entire input set terminates with an input `0' for c.

Output
For each test case in the input, print four lines. The first line contains the input data, viz., c, n, S, together with an integer w that spots the MWM and a letter q that identifies his quality. If MWM is spotted then 1 w n and the letter q is either `s' or `i' depending on whether the quality of MWM is identified as superior or inferior. If MWM is not among the look-alikes then w is equal to zero and the letter q is equal to `m', representing 'MWM missing'. In case the comparisons reveal that the claims of the professionals are faulty, then w is equal to `-1' and q is equal to `f' representing ``faulty comparisons and claims are not tenable''.The next three lines contain Ai, si, Bi, i = 1, 2, 3 where Ai, Bi are the groups for comparison at the i-th stage and si is the given outcome of the special compare operation. Print a blank line between outputs of two test cases.

Sample Input
1 2 3 4 5 6 7 8 0 1 1 1 1 2 1 1 1 3 1 1 8 8 8 8 8 8 8 8 HHH HHE HHL HEH HEE HEL HLH EEE

Sample Output
8 2 4 5 8 2 4 5 8 2 4 HHH 3 H 7 H 6 H HHE 3 H 7 H 6 E HHL 3 H 7 H 1 s 4 5 6 2 5 8 2 7 8 -1 f 4 5 6 2 5 8 2 7 8 5 i 4 5 6 2 5 8

1 4 1 1 1 5 1 1 1 6 1 1 1 7 1 1 1 8 1 1 1

5 8 2 4 5 8 2 4 5 8 2 4 5 8 2 4 5 8 2 4 5

6 L HEH 3 H 7 E 6 H HEE 3 H 7 E 6 E HEL 3 H 7 E 6 L HLH 3 H 7 L 6 H EEE 3 E 7 E 6 E

2 7 8 -1 f 4 5 6 2 5 8 2 7 8 3 s 4 5 6 2 5 8 2 7 8 6 i 4 5 6 2 5 8 2 7 8 -1 f 4 5 6 2 5 8 2 7 8 0 m 4 5 6 2 5 8 2 7 8

94. A doctor has a great reputation for his treatments. However his prescriptions are illegible. He alone and only his own chemist can read his prescriptions. Sometimes it is difficult even to identify the same medicine written in two different prescriptions. The doctor has a standard pattern of prescribing medicines. He has a standard set of N pet medicines outside which he never prescribes any medicine. For every pet medicine there is a set of related successor pet medicines. A pet medicine may appear in one or more sets of successor pet medicines. The doctor prescribes medicines in the form of a list. If he prescribes a medicine then he never repeats it in the same prescription. Further, when he prescribes a medicine then the next medicine, if any, in the prescription is one of the successor pet medicines and none of these successor pet medicines appears in the prescription subsequently. A team of handwriting experts and medical practitioners analyzed a large number of prescriptions of the doctor and made a possible list of his pet medicines. The medicines in this list are identified by N integers 1,2,..., N. For each pet medicine in the list, they also prepared a list of successor pet medicines one of which possibly succeeds the medicine in every prescription. A prescription has a list of p medicines. If some of the medicines in a prescription are identified then it is required to identify the unidentified medicines in the prescription. Write a program that will identify the unidentified medicines if one or more medicines in the list are given as identified.

Input
The input may contain multiple test cases with data from one or more expert teams. For each test case, the first line contains the expert team number n and the number N( < 500), of pet medicines identified by the team. Each of the next N lines contains a set of integers: the i-th line identifies the successor pet medicines of the i-th pet medicine. Each test case is related to a given prescription. There is a line that gives the number p. Next p lines identify some of the p medicines in the prescription. The i-th line contains j if the i-th medicine in the prescription is identified as j. If the ith medicine is unidentified then j is equal to 0. The entire input set terminates with an input `0' for n.

Output
For each test case in the input, print a line containing the expert team number n and the total number k (k 0)of possible solutions. Each of the next k lines contains a complete sequence of p possible medicines in lexicographic order. Print a blank line between two successive test cases.

Sample Input
1 2 1 5 2 1 4 0 3 0 0 2 3 1 2 1 2 2 4 4 0 2 1 0 1 2 4 2 5 4 5 3 3 2 4

6 4 5 6 4 6 3 6 4 5

Sample Output
2 3 5 4 3 5 1 0

95. A new township has been built over a rectangular plot of land dividing the whole area by a grid. The grid divides the whole plot into (m - 1) x (n - 1) big square plots for use as residential / commercial / industrial areas. Each square plot is divided into smaller plots and these are well connected by internal road network. However, the major road links in the township connecting all big square plots are the avenues running along the grid with m x n junctions. The junctions are assumed to be arranged in m rows and n columns and are denoted by (p, q), p = 1, 2,..., m, q = 1, 2,..., n. For an internal junction (p, q), the neighboring junction (p - 1, q) is assumed to be at the north of (p, q). In addition to the road network of the township there is a rectangular perimeter road that runs around the township with connections from each road junction located at the boundary of the township. An outline of the road links in the township is shown below where the perimeter road is indicated by the rectangle drawn around the network and a road junction at (p, q) with directions to four roads going out of the junction are indicated by

The traffic control department of the township enforces static traffic control rules that either permit or do not permit traffic out of a road junction in a given direction. At each road junction there are four traffic signals, one facing each of the four roads connected at the junction. Each of these signals is lighted either Green or Red according to whether traffic is or is not permitted out of the junction. A traffic in the perimeter road is permitted to enter the township through a road junction connecting the perimeter road if the traffic signal at the junction facing the perimeter road, is lighted Green. It is generally believed that moving along the perimeter road is more risky than moving along the township avenues. It is also believed that the risk while moving from a source junction to a neighboring destination junction in the township avenues is same whatever be the location of the junctions. Let this risk be R. The risk is additive in the sense that if one moves from a source junction to a destination junction through the township avenues, passing through k - 1 other junctions then the risk is equal to kR. When the perimeter road is used to move from a junction to another junction separated by k - 1 other junctions ion the boundary of the township then the risk increases by a constant factor f and the risk is equal to fkR, where f is a real constant that depends on the time of journey. In addition, for moving along the corners of the perimeter road there is an additional risk, it is estimated to be 2fR for each corner. Let the total risk in moving along a rout be denoted by FR. The factor F is called the risk factor of the rout. As an illustration it may be pointed out that the risk for moving from (1,2) to (2,1) is 2R if the movement is through the rout (1,2), (1,1), (2,1). So the risk factor F of this rout is equal to 2. However, the risk becomes 4fR (= 2fR + 2fR) if one moves along the rout (1,2), perimeter, (2,1) crossing the corner of the perimeter road once. In this case if f is defined to be 2.5 then the risk factor F is equal to 10.0. Given a source junction (a, b) and a destination junction (c, d ) when certain traffic control rules are under operation and the constant f is known, the problem is to find the total number s of the safest routs to move from the source to the destination and determine the risk factor F associated with the safest routs.Write a program to solve this problem.

Input

The input may contain multiple test cases.For each test case, the first line contains the case number c, the total number of rows m, and columns n, the total number r of source, destination pair for each of which the safest routs are to be found and the constant factor f. Each of the next r lines gives a, b, c, d indicating the {source (a, b) , destination (c, d )} pair for which the safest routs are to be found. The traffic signals at m x n junctions are given in row major order of the junctions in the next m x n lines. The traffic signals at a junction are represented by a string of four 0's and 1's, `0' representing a Green signal and `1' representing a Red signal. The signals are given in clock-wise order starting from the signal at the north. Thus if `0011' represents the four signals at a junction then the signal at the north is Green, the signal at the east is also Green while two other signals are Red. The entire input set terminates with an input `0' for the case number c.

Output
For each test case print the test case number c in one line. For each given {source (a, b), destination (c, d)}pair, print a, b, c, d, s and F as shown in the sample output. Print a blank line before printing output for the next test case.

Sample Input
1 4 5 2 2 1 1 1 4 0101 1001 0011 0011 1100 1010 1010 1001 1100 0110 0110 0011 1100 0011 0110 1010 0110 0110 0101 0101 2 4 6 2 1 3 0011 0011 1101 1011 1001 1101 0011 0111 0100 0110 1011 0101 1100 0110 1110 0110 0110 2 1.5 1 1

1 2 5

1000 1011 0001 0011 0101 0110 1110 0

Sample Output
1 2 2 1 1 1 5.5 1 1 4 1 1 4.0 2 2 1 3 5 6 19.0

96. Leaders of N political parties agree to have a round table conference to resolve a political issue through discussion. However due to animosity between parties and leaders some / all leaders may dislike sitting next to leaders specified by them. The problem is to determine, if possible, sitting arrangements around the round table so that a leader is not required to sit next to another leader disliked by him / her.Leaders are identified by integers 1, 2,...N. It may be noted that if a leader I dislikes sitting next to another leader J then the leader J may not necessarily dislike sitting next to I. However in such a case I and J can not sit next to each other because I dislikes J. Further, clockwise and anti clock-wise arrangements are considered identical. An arrangement is represented by a sequence of N integers 1, 2,...N indicating the relative positions of each leader beginning with leader 1. It is assumed that the last integer in the sequence and the integer 1 appearing in the first position are next to each other in the sitting arrangement. The arrangements are to be printed in lexicographic order.Write a program to print all possible sitting arrangements for the round table conference.

Input
The input may contain multiple test cases. The first line of each test case contains the case number c and the total number of leaders N( < 100). Each of the next N lines contains N zeros / ones. If dij denotes the j-th entry in the i-th line then dij is equal to 1 if leader i dislikes leader j, otherwise dij is equal to 0. It is assumed that dii is equal to 1. This is true for all i, j = 1, 2,..., N. The input terminates with an input `0' for c.

Output
For each test case in the input, first print, in a line, the test case number c and the total number k (k 0) of possible arrangements as shown in sample output. Each of the next k lines prints an arrangement in lexicographic order. Print a blank line between two successive test cases.

Sample Input
1 1 0 0 1 0 2 1 0 1 1 0 0 0 5 1 1 0 0 1 6 0 1 0 0 0 1 0 0 1 0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 0 1 0 0 0 1 0 0 1 0 0 0 1 1 1 0 1 0 0 1 1

Sample Output
1 2 1 1 0 2 5 2 3 4 6 5 2 4 3 6

97. The successful launching of third-generation (3G) mobile phone by the Japanese giant DoCoMo marked the beginning of an era in real-time multi-media inter-net communications at affordable cost. The F-TV or the Future TV has the reputation to venture into innovative TV programs that might attract large number of viewers in near future. In order to remain ahead in the race to have the largest number of viewers during a prime time slot in comparison to other TV channels, the management of F-TV plans to produce a TV program that will provide a large number of viewers with an opportunity to chat with a celebrity either in person or in real-time virtually using mobile phones and get cash prizes in the process. The planned TV program consists in having a celebrity on each show as the anchor of the chat show and a selected number of viewers as 'real' participants. Any number of remote viewers may also join the program during the show as 'virtual' participants using their 3G mobile phones from anywhere in the world. Each participant, male or female, real or virtual, is enrolled for the show and is given a unique token serial number on first come first served basis. Towards the end of the show the anchor runs a computer program that selects participants from among the enrolled participants and announces cash prizes for the selected participants. There is a possibility that no participant is selected for a prize; in such a case the anchor announces the decision accordingly. The computer program selects the participants to get prizes in a simple way. Let n be the total number of participants, real or virtual. Each participant is given a token serial number p, p = 1, 2,..., n. Let xp, be equal to 0 if the participant having the token serial number p, is female, otherwise xp is equal to 1. The input to the program is the string x = (x1, x2,..., xn) of length n on the alphabet {0,1}. The program finds the longest palindromes contained in x ( i.e. the longest sub-strings made up of elements of x each of which reads the same backward as forward). Let there be k such palindromes and let U be the union of all these palindromes. The program deletes U from x. It repeats the process with the reduced string x successively until there is no palindrome of length 3 or more. Finally it finds the elements of x, if any, which are retained in the process. For example, let n = 37 and x = (0110 1110 1101 1011 0111 0101 1101 0010 0101 1) where the elements of x are written in groups of four followed by a blank character, for easy readability. The sub-string (x3,..., x22) =(10 1110 1101 1011 0111 01) is of length 20 and is the longest palindromes in x. If this sub-string is deleted then the string x is reduced to (x1, x2, x23, x24,..., x37) with elements (0101 1101 0010 0101 1) which when reduced further gives (x1, x2, x23, x24) with elements (0101). Finally, since the longest palindromes in (0101) are (010) and (101) , each of which is of length 3 and their union is the entire string under consideration, all the four elements are deleted. Hence, no element of x is selected.

Input
The input may contain multiple test cases. For each test case, the first line contains two integers the case number c and the length n of the given string. The string x is given in one or more lines in groups of four elements separated by a blank character; the last group in the string may contain less than four elements. The string is terminated with the character $ which is not considered as a part of the string. The entire input set terminates with an input `0' for c.

Output
For each test case in the input, print the test case number c and the number k of participants selected for the prize. In next k lines, print the token serial numbers of the participants selected for the prize in ascending order. Print a blank line before printing the output of the next test case.

Sample Input
1 37 0110 1110 1101 1011 0111 0101 1101 0010 0101 1 $ 2 62 1011 0001 1110 1010 1111 0010 1010 0111 1101 1010 0110 0011 0110 0011 0111 10 $ 0

Sample Output
1 0 2 1 1

S-ar putea să vă placă și