Olympiad in Mathematics - Category Programming

Problem Set of the Third Round

2000/01



The first day of competition

P-III-1

Mr. Kas Parrow was an eager chess player. He was often missing a player with equivalent skills and he was bored by playing alone (he always discovered all well-prepared traps) and thus he made up the following game:

The task is to place N rooks on a chessboard with dimensions NxN in such a way that no two of them threaten each other. However, to make the game more interesting, for each rook there is a predetermined rectangle inside of which it is to be placed.

Task:

Write a program, which can play this game. The input contains the dimension of the chessboard N and descriptions of N rectangles - quadruples Ax, Ay, Bx, By, 1 <= Ax <= Bx <= N, 1 <= Ay <= By <= N, where Ax, Ay are coordinates of top left corner of the rectangle for rook x, and Bx, By are coordinates of the bottom right corner the same rectangle. Rows are numbered from top down, 1 to N, and columns from left to right, 1 to N. The program will write an arbitrary correct layout of the rooks on the chessboard or print a message that such placement does not exist.

Example:
Input:

N = 4
1 1 1 1
4 4 4 4
1 1 3 3
3 2 4 4
Output:
(1,1) (4,4) (2,2) (3,3)

P-III-2

Write a program that will read a positive integer N and will write the lowest integer x, which is divisible by N and contains only digits 1 and 0 (in decimal number system). In case ther is no such number, the program will inform about it.

Example:

N = 6

Output: 1110.


P-III-3

Let's start with several definitions: Tiles are squares of an equal size with colored edges. A particular assignemt of colours to edges is called type of tile and is represented by an ordered quadruple (l,p,h,d) specifying the color of left, right, top, and bottom edges in this order. To simplify our work, we will use different symbols - letters, digits, etc. instead of regular color names. For example a tile of type (1,2,3,4) looks like this:

Image: tile

The space we want to tile (called wall) has a shape of a rectangle of size m times n (both m and n are natural numbers; the unit is the length of the edge of one tile). The sides of the rectangle are divided into segments of unit length. Each segment is assigned a color. Our goal is to tile the wall with the tiles in such a way that each of the m*n unit squares of the wall will contain exactly one tile, the neighboring tiles will be facing each other with edges of the same color and the tiles on the sides will be facing the sides of the rectangle always with the edge of the same color as is the color of the corresponding segment of the wall border. The tiles can not be rotated.

Example:

Figure: correct and incorrect tiling

Tiling can be easily used to solve tasks, in which the result is a simpe "yes" or "no" answer. To transform such a task into a tiling problem, we can construct a suitable set of tile types (these are independent from the input, and are fixed for a given problem). Then we color the segments of one side of a sufficiently large wall with colors according to the problem input. The remaining sides are painted with one color and the the transformed task is whether this wall can be tiled or not. The result should be the same as is the result of the corresponding task.

The width of the wall will be always the same as is the length of the input to the original problem. The height of the wall will be the lowest possible, for which there exists a tiling using the designed set of tiles.

This way of computation resembles traditional programming. The designed set of tiles corresponds to a computer program and the required height of wall corresponds to the running time of the program - thus we will try to minimize it in our solutions.

More formally, a tiling program is an ordered quadruple D=(T,l[0],p[0],d[0]), where T is a finite set of tile types {(l[1],p[1],h[1],d[1]), ...,(l[k],p[k],h[k],d[k])} and l[0], p[0] and d[0] are border colors. A decision problem P(x) is a task to determine whether the input x (a finite sequence of symbols (i.e. colors) from a predetermined finite set of symbols) has the required property P. A tiling program solves a decision problem P(x), if P(x)="yes" if and only if there exists such v>0 that it is possible to tile a wall with dimensions |x| times v using tile types from the set T, where the top side of the wall is painted correspondingly to the input x, and the left, right, and bottom sides are painted by colors l[0], p[0] and d[0] in this order. It is possible to use as many tiles of each type as needed. The complexity of a tiling program D for a given input x is the lowest v, for which the tiling is possible; if such v doesn't exist, and thus P(x)="nie", the complexity is defined to be zero. The complexity of the program is a function of the input length n, and its value is the maximum of all complexities of tiling programs for different inputs of the length n.

In addition to the decision problems, tiling programs can be used for computing the values of functions. Computation of a function value f(x) can be easily transformed to a special decision problem P(x,y) = "is y = f(x)?", which is true for only one value y for each x. In addition, the x and y can be given as a single input so that the tile colors will correspond to ordered pairs of values.

Example:

We will construct a tiling program, which will compute a division by 3 given an input binary number (the output will be also given in binary and we can assume that the input number is divisible by 3). In other words, for a given sequence of pairs (x1, y1), ..., (xn, yn), the program will determine whether <y1, ..., yn> = <x1, ..., xn>/3.

The solution is based on standard paper and pencil division algorithm (which is independent from the number system): let z0=0 and we will consequently compute the values zk=(2.zk-1+xk) mod 3 and yk = floor((2zk-1 + xk)/3). Now we can prove using induction that for each k,

<x1, ..., xk> = 3.<y1, ..., yk> + zk.

For k=0, the relation holds. Assuming it holds for k-1, we get:

<x1, ..., xk> = 2 . <x1, ..., xk-1> + xk =
= 2 . (3 . <y1, ..., yk-1> + zk-1) + xk =
= 3 . 2 . <y1, ..., yk-1> + 2 . zk-1 + xk =
= 3 . 2 . <y1, ..., yk-1> + 3 . yk + zk =
= 3 . <y1, ..., yk-1> + zk.

Now it is sufficient to choose the following set of tiles:

Figure: set of tiles

the left and right borders have the color 0, and the bottom has the color "dot".

These tiles can form only walls with single line ("dot" is not found on top of any tile). In any possible tiling, the k-th tile has zk on the right edge, and for any pair (xk, yk), the following is true about its top edge: yk = floor((2.zk-1 + xk)/3). In other words, this tiling corresponds to values computed by our algorithm.

Task

Construct a tiling algorithm, which will sort a sequence of zeros and ones in an increasing order, i.e. it will answer yes to a sequence of pairs of zeros and ones (x1, y1), ..., (xn, yn) if and only if the sequence y1, ..., yn is a sequence, which can be obtained by sorting the sequence x1, ..., xn in an ascending order, i.e. y1<= ... <=yn and the sequences x and y contain the same elements (in possibly different order).

Example:

The program will answer "yes" to the sequence (1,0), (0,0), (0,0), (1,1), (0,1), (1,1), and it will answer "no" to sequences (1,1), (0,0), and (1,0), (1,1).


The second day of competition

P-III-4

A new text editor needs a text-formatting component. The editor works in a text mode with non-proportional font (i.e. all characters including the space and other characters have the same width). The editor is simple and doesn't support word splitting and hyphenating. The program for the formatting component will always be used for formatting one paragraph of text only. Each consecutive sequence of non-white characters (space and new line) that is surronded by white characters or beginning or end of a line is considered to be a word.

The formatting tasks consists of generating a proper layout of words into individual lines so that the whole text is aligned into a block (i.e. to left and right border) given a length of the line. The distances between words filled with spaces should be placed as evenly as possible. These general requirements are specified in detail as follows: The numbers of spaces placed between words placed on the same line can differ by at most one (with the excpetion of the last line in the paragraph). The first word in the line should not have any space in front and the last word in the line should not be followed by any space. If there is only 1 word in a line, the placement of the spaces can be arbitrary. Words in the last line of a paragraph should be separated by exactly one space and there should be no space in front of the first word.

If a text satisfied the above requirements, the quality of formatting is evaluated using a penalty score. The score for the whole paragraph is a sum of scores for its individual lines. The score for a single line is given by a function F(Width, Chars, Words, Last), where Width is the width of the page (i.e the number of characters on line including all the spaces), Chars is the number of non-white characters on the line, Words is the number of words on the line and Last specifies whether the evaluated line of the paragraph is the last one or not.

The evaluation function in programming language C looks like as follows:

int F(int Width, int Chars, int Words, int Last)
{
  int Spaces = Width - Chars - Words + 1;   /* number of obsolete spaces */
  int BasePen = LINEPENALTY;                /* basic penalty for a line */
  if (Spaces < 0)                           /* if text doesn't fit to a line */
     return INFTYPEN;
  if (Last)                                 /* Last line? */
  {
    if (4*(Chars + Words - 1) <= Width)     /* is the last line too short? */
      BasePen += SMALLLINEPEN;
    return BasePen;
  }
  if (Words == 1)                           /* Only a single word on a line? */
    BasePen += SINGLEWORDPEN;
  return Spaces * Spaces + BasePen;         /* Evaluation of the whole line */
}
In programming language PASCAL, the function F looks similar:
function F(Width, Chars, Words: Integer; Last: Boolean): Integer;
var Spaces : Integer;     { number of obsolete spaces }
    BasePen : Integer;    { basic penalty for a line }
begin
  BasePen := LINEPENALTY;
  Spaces := Width - Chars - Words + 1;
  if Spaces < 0 then     { text doesn't fit line? }
    F := INFTYPEN
  else if Last then begin   { last line? }
    if 4*(Chars + Words - 1) <= Width then   { line too short? }
      Inc(BasePen, SMALLLINEPEN);
    F := BasePen;
  end
  else begin
    if Words = 1 then      { only single word on the line? }
      Inc(BasePen, SINGLEWORDPEN);
    F := Spaces * Spaces + BasePen;   { Evaluation of the whole line }
  end;
end;
The constant values are as follows:

Your task is to format a paragraph of text of a given width of line with as high quality as possible, i.e. to satisfy all the binding requirements for text-formatting and obtain as low penalty score using function F as possible.

Input:

The input file FORMAT.IN contains a required width of page on the first line. The following lines contain the text of the paragraph that is about to be formatted. You can assume that all lines contain at most 100 characters, there are no leading and trailing spaces, and the words are separated by exactly 1 space. The whole input file including the spaces does not contain more than 10000 characters.

Output:

The output file FORMAT.OUT should contain the formatted paragraph given the requirements specified above.

Example:

FORMAT.IN
40
Each section in this document will have the string "
" at the right-hand side of the section title. Each subsection will have "" at the right-hand side. These strings are meant to make it easier to search through the document. FORMAT.OUT (one of the possible solutions; symbol '_' depicts a space) Each__section__in__this__document___will have__the__string__"
"__at___the right-hand_side_of__the__section__title. Each_subsection_will_have_"" at_the_right-hand__side.__These__strings are_meant_to_make_it__easier__to__search through_the_document.

P-III-5

In the city Freemine, there has been an explosion of tourism. In order to support it, the local authorities decided to establish a travel agency TIKS-Tour. Their mission is to run several bus sightseeing tours around the town. Your program is about to suggest the routes for individual bus lines according to the requirements of the authorities, or to find out that the requirements cannot be satisfied.

The city consists of crossings, which are interconnected by streets. Each street connects exactly two crossings. Two crossings can be connected by more than one street. The place where only one (or two) street ends is also called a crossing.

The city council has the following requirements: In order to allow a comfortable sightseeing of each street in the city and to save the costs, each street should be visited by exactly one bus route. No bus route can pass through any crossing more than once. The routes should be cyclic, i.e. the start and end is at the same crossing.

Input:

The first line of the input file CYCLIC.IN contains two integers separated by a space - the number of crossings N (1 <= N <= 120) and the number of streets M. The crossings are numbered from 1 to N. The following M lines of the input file contain descriptions of individual streets in the city. Each line contains two integers - the crossing numbers connected by a street (the first number in each line is smaller than the second one). These lines are sorted according to the first number, if there are more streets with the same first number, they are sorted according to the second number. You can assume that there are no more than 200 streets connecting any two crossings.

Output:

The output file CYCLIC.OUT will contain a line for each bus route. Each route is described as a sequence of crossing numbers that the route is passing through. The first and last number at each line should be the same. The numbers should be separated by space. If it is not possible to design the routes to meet the requirements, the output file will contain a single line with text "Routes impossible."

Example:
Input:

5 12
1 2
1 2
1 2
1 2
1 3
1 3
2 3
2 5
3 4
3 5
3 5
4 5

Output:

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

Input:

3 4
1 2
1 2
1 3
2 3
Output:
Routes impossible.