Editorial for COCI '10 Contest 2 #2 Napor


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

This problem can be divided into two subproblems: extracting the numbers, and sorting them.

Extracting the numbers

The first thing to notice is that numbers that appear can have up to 100 digits, and cannot fit within a 64-bit integer data type (long long in C++, int64 in Pascal). We must have our own representation of a number that big, and the simplest way to do this is to store them as strings.

We process text line by line, and traverse each line from left to right, keeping track of consecutive sequences of digits. We are going to need the following variables:

  • num - array of found numbers
  • X - part of the number found so far
  • flag S

We use flag S to handle leading zeros. If S = 0, we haven't found any digits so far. If S = 1, we have found a sequence of zeros. While S = 1, we don't add digits to our number X. We start doing that only after having found some non-zero digit, and mark this by setting S = 2. We have to be careful to add numbers that are equal to zero. The exact algorithm is shown below.

For each character c in left to right order:

  • if c is a letter
    • if S = 0 - do nothing
    • if S = 1
      • add zero to num
      • S = 0
    • if S = 2
      • add X to num
      • X = empty string
      • S = 0
  • if c is a digit
    • if S = 0 and c = 0
      • S = 1
    • c \ne 0 or S = 2
      • append c to X
      • S = 2

Notice that the algorithm above won't add to array num any number located at the end of the line. We must check for this ourselves, or append any letter to the line before running the algorithm.

Sorting the numbers

In order to sort the array num, we need a way of comparing two numbers stored as strings. If strings are not of equal length, it's easy to see that the shorter one is smaller. Otherwise, we need to find the leftmost position in which they differ, and compare characters at that position. Of course, if they are equal, we won't find such a position.

Once we have a compare function for our numbers, we must use some sorting algorithm. Since there are at most 500 numbers in the input text, any algorithm will be fast enough. We can use a simple one, like bubble sort or insertion sort.


Comments

There are no comments at the moment.