# © 2008 Павел Иржавский, Владимир Керус, Никита Лесников © 2008 Irzhavskij Pavel, Kerus Vladimir, Lesnikov Nikita.

## Presentation on theme: "© 2008 Павел Иржавский, Владимир Керус, Никита Лесников © 2008 Irzhavskij Pavel, Kerus Vladimir, Lesnikov Nikita."— Presentation transcript:

Problem A: Littera

Solution Stage 1 Remove from both messages all non-letter symbols. Stage 2 Calculate key text that transforms plaintext into ciphertext

Solution Stage 3 Calculate minimum possible length of key. Suppose length of the shortest possible key is K and length of the key text is N. Then N – K is length of the longest substring of key text that is both prefix and suffix simultaneously. This value can be calculated using Knuth–Morris–Pratt algorithm.

Solution Stage 4 Find lexicographically smallest cyclic shift of first K symbols of key text. One of possible approaches is Duval algorithm. All algorithms used in solution take linear time.

Problem B: Conversions

Solution Stage 1 If B 1 < 0 then convert source number into numeral system with base |B 1 |: 1.Replace digits on even positions (counting from the right) by their negative values. 11012 -3 → 10 2 3 2.Normalize number. Moving from right end to the left bring digits into range 0..B 1, changing in case of need more left digit. 10 2 → 1 22 → → 1-2222 → 01222

Solution Stage 2 Convert number from numeral system with base |B 1 | into numeral system with base |B 2 |. 1222 3 → 125 6 Stage 3 If B 2 < 0 then convert number into numeral system with base similarly to the first stage. 125 6 → 1-25 -6 → 245

Problem С: Divisibility by 396

Solution 396 = 4 * 9 * 11 Criterion of divisibility by 4: number written by two last digits is divisible by 4. Criterion of divisibility by 9: sum of all digits is divisible by 9. Criterion of divisibility by 11: difference of the sum of digits on even positions and the sum digits on odd positions is divisible by 11.

Problem D: Worm on an Apple

Solution Consider plane containing points A, B and center of the apple. AC = AB/2 If CO > P, then wormhole doesn’t go through the core and this way takes AB/v2 time units. Otherwise And it takes (AB-2CD)/v2 + 2CD/v1 time units to gnaw through apple.

Solution Length of the shortest way along surface is equal to value of angle AOB (in radians). AOB = 2arccos(AC/AO)

Problem E: Extremums

Nothing to explain here… The task is trivial – just implement what you’re being asked for No pitfalls

Problem F: Military Bases

Solution Stage 1 Sort vertices of graph topologically. Stage 2 Consider vertices in reversed order and make greedy approach to find maximum independent set.

Problem G: Forest

Quick summary Condensed statement looks something like that: Given simple polygon of N vertices, determine for each of the given M points, whether it lies inside, outside, or on the border of a polygon. Constraints: 1 ≤ N, M ≤ 10 5, 0 ≤|X i |,|Y i | ≤ 10 5

Naïve solution For each of the points: –Plot a ray from it in any direction –Determine the number of intersections between the ray and the polygon boundary in linear march –If the number of intersections is even, the point lies outside the polygon; if it’s odd – inside the polygon –Testing whether the point is on the border is trivial

Possible pitfalls When the ray intersects several boundary segments at once, it’s easy to disguise one intersection points for many, leading to incorrect test result. Need careful coding to resolve that.

Need for a better solution Complexity is still O(nm), which averages at 10 10 “primitive operations” for carefully designed test cases. That’s way too slow. Different optimizations can’t change the quadratic nature of that algorithm – we need a better one.

Good algorithm Based on a similar idea, however we’ll use a better technique for determining the number of intersections Special data structures will enable us to find the number of intersections in logarithmic time

Preprocessing step First, we split the boundary of the polygon into monotone sections – that is, continuous sections of increasing Y coordinate (sections of decreasing coordinates should be reversed). This can be trivially done in O(N) time & space.

Example Different colors denote each of the monotone sections of the simple polygon

Preprocessing step (contd.) For each of the monotone sections, generate enter & exit events. Sort events lexicographically 1 Sort query points lexicographically 1 1. Sort by Y coordinates first, then sort points with equal Y by X

Resolving step Process query points in lexicographic order: –Emulate all the events you encounter on the way, pushing the corresponding section into a balanced binary tree on enter events and removing it on exit events –Use a custom comparer to resolve relative order of monotone sections at each moment in time –Maintain a subtree size field in each of the balanced tree nodes

Resolving step (contd.) Crucial things to notice: –Relative order of the sections doesn’t change between the events –Using the subtree size information, we can determine the number of sections lying to the left of the current query point in O( log N ) time using classical dynamic order statistic algorithm.

A pitfall Horizontal sections cannot be resolved using the abovementioned algorithm The cause of the problem is that for a horizontal section, enter and exit events overlap. We can resolve all such cases in an additional linear pass over horizontal sections only.

Complexity analysis Insertion and deletion into/from the balanced binary tree occurs in O( log N ) average/worst case time, depending on implementation (different reference implementations use cartesian & red- black trees) Each event, and, correspondingly, each section gets inserted/removed into/from tree exactly once. Dynamic order statistic resolution of each point occurs in O( log N ) time Underlining all the above analysis, we get a time complexity of O( max(N,M) log N )

Problem H: Shake

Quick summary Condensed version of the statement: Given a string consisting of small latin letters and the sentinel symbol \$, which is assumed to be less than all the other elements of the alphabet, a transformation called “shaking” of the string can be defined. Task requirement: given a “shaked” string, restore an “original” one

Quick summary (contd.) “Shaking” of a string S consists of several steps: – Write out all the N (N = |S|) left rotations of a string –For each of them, form a triple (T, P, L), where T – length-K (1 ≤ K ≤ N-1, K=2 t for some natural t) prefix of the corresponding left rotation P – position of the first symbol of the corresponding left rotation (starting from zero) in original string S L – last symbol of the corresponding left rotation

Quick summary (contd.) “Shaking” a string consists of sorting the triples using a custom comparer: –First compare the T (for “text”) elements of triples, and iff they are equal – compare the P (for “position”) fields. Write out the L fields of the triples in sorted order continously, yielding the “shaken” string.

Quick summary (contd.) Continuing the example… Sorted triples “Shaken” string: ar\$drcaaaabb (\$a, 11, a) (a\$, 10, r) (ab, 0, \$) (ab, 7, d) (ac, 3, r) (ad, 5, c) (br, 8, a) (br, 1, a) (ca, 4, a) (da, 6, a) (ra, 9, b) (ra, 2, b)

Crucial observations We can get some useful ideas from studying the direct “shaking” transformation For example, the custom comparer mentioned in the statement does nothing more than a usual stable sort – it just sorts elements by their keys (read prefixes), leaving elements with the same keys in the same order they were in original unsorted sequence.

Crucial observations (contd.) One of the most well known algorithms for doing stable sorting is least significant digit radix sort: –If you want to sort a sequence of M-element keys lexicographically and in stable order, it’s enough to have an algorithm for sorting 1- element keys stably: simply apply the algorithm to your sequence, using the digits in the order from least significant to most significant as the keys

Restoration idea That’s no coincincidence; in fact, these observations can be proven quite naturally by studying properties of left rotations of one string. Actually, the relations are very similar to ones arising in subquadratic suffix sorting. The invariance of two adjacent columns means that, if P is a permutation which performs step 1 of the LSD Radix Sort, we can obtain the configuration at step n by applying P n-1 to sorted last column

Restoration idea (contd.) We may apply the P -1 in the appropriate powers to the “shaken” string K times in a row to restore all the K-prefixes of corresponding left rotations in sorted order: P -1 P -2 P -3 P -4 a | \$ r | a \$ | a d | a r | a c | a a | b a | c a | d b | r a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra a | \$ab r | a\$a \$ | abr d | abr r | aca c | ada a | bra a | cad a | dab b | ra\$ b | rac a | \$abr r | a\$ab \$ | abra d | abra r | acad c | adab a | bra\$ a | brac a | cada a | dabr b | ra\$a b | raca

Restoration idea (contd.) So, given O(nk) space & time, we can restore the T & L fields of all the triples in sorted order. Is this information enough to get the original string back?

Restoration idea (contd.) It turns out that yes, and it can be done quite trivially: –the K-prefix following the sentinel (\$) sign is for sure to belong to the left rotation equal to S –Using the sentinel sign and K-1 first symbols of the corresponding prefix, we can get the K- prefix following the next to last symbol. The symbol preceding the last occurrence of this K-prefix will be the one standing on position N-1

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra Next to last symbol

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra Next to last symbol Symbol at position N-2

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra Next to last symbol Symbol at position N-2 The last occurrence of the K-prefix Gives the symbol at position N-3

Restoration idea (explanation) a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra Next to last symbol Symbol at position N-2 The last occurrence of the K-prefix Gives the symbol at position N-3 And so on…

More observations P (the stable sorting permutation), applied to the row of Nth symbol of S, will yield a position with a K-prefix of (N-1)-th symbol (trivially follows from the above LSD Radix Sort properties) So, we don’t need to know the values of the K-prefixes themselves to “jump” from position to position; it’s enough to adjust it according to prefix boundaries

Pseudocode for restoration T[ i ] = position of the first row with the same K- prefix as the row I C[ i ] = number of rows with K-prefix equal to row’s i TC a | \$a r | a\$ \$ | ab d | ab r | ac c | ad a | br a | ca a | da b | ra 012234556788012234556788 112011201120112011201120

Pseudocode for restoration (contd.) for (int i = n-1; i >= 0; --i) { d[ i ] = s[ si ]; si = RP[ si ]; si = T[ si ]; si += --C[ si ]; } wheres – “shaken” string si – current row (index of \$ at start) d – restored string RP – P -1

Computing K-prefix boundaries To compute T & C arrays, only K-prefix boundaries are needed, not their values Restoring context boundaries can be done in O( N log N ) time using the “doubling” technique used in many widely known string algorithms (for example, suffix sorting by Manber & Myers, or direct BWT by Larssen-Sadakane)

Computing K-prefix boundaries (contd.) The main idea is that, given K-prefixes, we can in linear time restore the context boundaries for 2K-prefixes. Base for inductive algorithm is obtained at K=1, which is achieved by direct radix sorting the first column Everyone interested is directed to classic books on string algorithms

Complexity analysis Time to restore context boundaries – O(N log K); K as power of two restriction is not strict and is mainly intended to simplify coding Time to construct T & C arrays and to restore original string – O(N) Total complexity – O(N log K), with quite low asymptotic constant

Problem I: Walking the Labyrinth

Solution Stage 1 Let us number possible places for mine by numbers 1..К and for every possible place find length of the shortest path to the safe cell and backwards. Such path may not exist.

Solution Stage 2 Consider additional states 0..К for every cell of grid. 0 – character is in this cell and he didn’t explode the mine. 1..К – character is in this cell and he exploded mine in place with number equal to number of state

Solution Stage 3 Build graph, which vertices are states of cells and edges are added in following way: 1. Between neighbouring empty cells with equal states. Length of the edge is 1. (1, 1, 2) – (2, 1, 2)

Solution 2. For cells where mine can be exploded (and exists reachable safe cell) between state 0 and state equal to number of this cell. Length of edge is equal to length of shortest path to safe cell and backwards. (1, 1, 0) – (1, 1, 1)

Solution 3. Between cell where mine can be exploded to the neighbouring cell with wall and both cells have state equal to the number of cell with mine. The length of the edge is 1. (1, 1, 1) – (2, 1, 1)

Solution Stage 4 Find the shortest paths from cell A and state 0 to the cell B with states 0..K and choose minimal among them. If none of the paths exists, it’s impossible to get from A to B.