Editorial for COCI '10 Contest 2 #2 Napor
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 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:
- - array of found numbers
- - part of the number found so far
- flag
We use flag to handle leading zeros. If , we haven't found any digits so far. If , we have found a sequence of zeros. While , we don't add digits to our number . We start doing that only after having found some non-zero digit, and mark this by setting . We have to be careful to add numbers that are equal to zero. The exact algorithm is shown below.
For each character in left to right order:
- if is a letter
- if - do nothing
- if
- add zero to
- if
- add to num
- empty string
- if is a digit
- if and
0
-
0
or- append to
- if and
Notice that the algorithm above won't add to array 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 , 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 numbers in the input text, any algorithm will be fast enough. We can use a simple one, like bubble sort or insertion sort.
Comments