2017 Mini Competition 0 M1701-5: Tony Wong M1706: Alex Tung (story by Tony Wong) http://m.star.naver.com/GFRIEND Yuju SinB /news/end?id=7941357

Eunha Yerin

Sowon “ M1701 - Hearts

https://youtu.be/bwTVerz9X3c 2017 Mini Competition 0 3

M1701 - Hearts

▸ Each small heart and large heart requires exactly 1 Buddy ▸ Each extra large heart requires 2 extra Buddies ▸ These 2퐷 Buddies can make 2퐷 mini hearts ▹ 퐴 ← max⁡(0⁡, 퐴 − 2퐷) ▸ Finally, 퐴/2 additional Buddies are required to make the remaining mini hearts ▸ long long is required

2017 Mini Competition 0 4 M1702 – Archery

http://ent.mbc.co.kr/content/4918 2017 Mini Competition 0 5

M1702 - Archery ▸ Compute the Euclidean distance of the center of the arrow to the origin: 푑 = 푥2 + 푦2 ▸ The score of the arrow is the max 푝 ∈ 1, 2, 3, … , 10 such that 푑 − 푟 ≤ 40(11 − 푝) ▸ To avoid precision error, we square both sides of the inequality 푥2 + 푦2 ≤ [40 11 − 푝 + 푟]2 ▸ To further avoid precision error, we store 푥, 푦 and 푟 using integers by multiplying the numbers by 10 (i.e. 푟 = 12⁡for 1.2mm) 푥2 + 푦2 ≤ [400 11 − 푝 + 푟]2

2017 Mini Competition 0 6 M1703 – Photo Collage Jeremy's favourite photo

http://childyenni.tistory.com/11 2017 Mini Competition 0 7

M1703 – Photo Collage

▸ How to represent the photos? ▹ Sowon, Yerin, Eunha, Yuju, SinB, Umji ▹ Method 1: Index the members using 0, 1, 2, 3, 4, 5. Create a 2D boolean array A of size N x 6. Set A[i][j] to true if member j is present in photo i ▹ Method 2 (better): Index the members using 1, 2, 4, 8, 16, 32. Sum up the numbers of the members present in the photo For example, we use 1 + 8 + 32 = 41 to represent a photo containing Sowon (1), Yuju (8) and Umji (32)

2017 Mini Competition 0 8 M1703 – Photo Collage

▸ Subtask 1: Each photo contains exactly 3 members ▹ Sowon, Yuju and Umji (1 + 8 + 32 = 41) can be paired with Yerin, Eunha and SinB (2 + 4 + 16 = 22 = 63 - 41) ▹ The 10 possible pairings are: 7 – 56 11 – 52 13 – 50 14 – 49 19 – 44 21 – 42 22 – 41 25 – 38 26 – 37 28 – 35 ▹ If we have a frequency array f that contains the count of each kind of photo, the answer would be: f[7] * f[56] + f[11] * f[52] + ... + f[28] * f[35]

2017 Mini Competition 0 9 M1703 – Photo Collage

▸ Subtask 2: Each photo contains exactly 2 members ▸ 6C2 = 15 kinds of photos with 2 members ▸ For i = 3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 33, 34, 36, 40, 48 ▹ For j = 3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 33, 34, 36, 40, 48 ▹ Make sure that no members are present in both i and j ▹ This can be done using binary operators: (i & j) == 0 ▹ answer += f[i] * f[j] * f[63 - i - j] ▸ Output answer / 6

2017 Mini Competition 0 10 M1703 – Photo Collage ▸ The task can be solved using Dynamic Programming ▸ dp[x][y] = The number of ways to make collage containing the members y (binary representation) using only the first x photos ▹ x = 0 .. N and y = 0 .. 63 ▸ Initially, dp[0][0] = 1 and dp[0][1..63] = 0 (There is one way to make a collage with no one in it using no photos) ▸ Consider the photos one by one, if i-th photo has members z (binary) ▹ For j = 0 .. 63, we try to combine the photo with the collages having j ▹ dp[i][j] = dp[i - 1][j] + dp[i - 1][j - z] if (j & z) == 0 ▹ dp[i][j] = dp[i - 1][j] if (j & z) != 0 ▸ Finally, answer = dp[N][63] have same members, ▸ Optionally save memory using dp[j] += dp[j - z] not allowed to combine 2017 Mini Competition 0 11 M1704 – Outfit Numbers

https://youtu.be/MZ6o8jT2PXo 2017 Mini Competition 0 12

M1704 – Outfit Numbers

▸ Subtask 1: N <= 10 ▹ Can be solved by O(2N N) exhaustion ▹ Each person has two options: month (0) or day of month (1) ▹ For example when N = 3, try these 23 = 8 combinations: ▹ 000, 001, 010, 011, 100, 101, 110, 111 ▹ For a combination, check whether two chosen numbers are the same in O(N) time

2017 Mini Competition 0 13 M1704 – Outfit Numbers

▸ One important observation is when N >= 32, there is no solution ▸ Or generally, if the number of distinct integers in the input > N, there is no solution ▸ One way to cut down the search tree: ▹ Backtrack immediately if two persons is assigned the same number ▸ Or, exhaust the other way: ▹ For each number 1, 2, ..., 31 either skip it or assign it to one person ▹ Backtrack when number of numbers left < number of unassigned persons ▸ The constraints are small enough for these to pass

2017 Mini Competition 0 14 M1704 – Outfit Numbers

▸ In fact, this task's constraints are so special that it can be solved using many ways: ▹ If any valid assignment is allowed, the task can be modelled as 2-SAT

▹ The ith person has boolean variable 푏푖 – whether the month is taken ▹ If the ith person's month is same as the jth person's month, person j must take the day of month. Therefore, ⁡푏푖 → ¬푏푗 (푏푖 implies not 푏푗) ▹ 2-SAT solved by finding Strongly Connected Components in the Implication Graph (e.g. Tarjan's Algorithm) ▹ Alternatively, use network flow algorithms to determine validity

2017 Mini Competition 0 15 M1704 – Outfit Numbers

▹ Take an input (M, D) as an (undirected) edge connecting nodes M and D ▹ Assignment is done by directing the edges ▹ Valid iff every node has in-degree at most 1 ▹ If solution exists, any connected component with K nodes must have at most K edges ▹ K - 1 edges: tree • Direct the edge that appears first in input • The remaining part is solved similarly ▹ K edges: 頂環樹 (cycle + many branches) • Only two ways to direct the edges 2017 Mini Competition 0 16 M1705 – Slippery Stage

https://youtu.be/41Sh-RYHiNU 2017 Mini Competition 0 17

M1705 – Slippery Stage

▸ Subtask 1: Stage has only 1 row ▸ There is only one optimal path from one cell to another ▸ For example, to move from c1 to c2 (assume c2 > c1), add the following to the answer

▹ S1, c1+1 + S1, c1+2 + S1, c1+3 + ... + S1, c2

2017 Mini Competition 0 18 M1705 – Slippery Stage ▸ We can model the stage as a directed weighted graph ▹ NxM nodes ~4NM edges ▸ Weighted graph shortest path can be found using Dijkstra's Algorithm – O(NM lg NM) ▸ Performing Dijkstra's once per query is not efficient enough ▸ Instead, precompute all-pairs distances by running Dijkstra's NM 2 2 times – O(N M lg NM) and answer each query in O(1) time – 80% ▸ Notice that the max distance is small ▹ Use an array of queues instead of priority queue: O(N2M2 ) – 100%

2017 Mini Competition 0 19 M1706 – Anniversary Gifts

https://www.facebook.com/HKGBUDDIES/photos /a.2298324910308451.1073741836.229777703 2017 Mini Competition 0 20 0363239/2354372181370390/?type=3&theater

Mini-Comp 0 Q6 Solution

Alex Tung

February 14, 2017

Simplifying Assumptions

We make several assumptions before explaining the solution.

• There are N positions and each time we move clockwise by K steps. Let g = gcd(N,K). The result is unchanged if we replace (N,K) by (N/g, K/g). From now on, assume gcd(N,K) = 1.

• The case N = 1 is trivial. From now on, assume N > 1.

• Now, we 0-index the presents and choose A ∈ [0,N) such that AK ≡ 1 (mod N). We can remodel the task as one which asks whether the permutation (0, A, 2A mod N, 3A mod N, ..., (N − 1)A mod N) is odd or even. (An odd permutation is one that has an odd number of inversions. An even permutation is one that has an even number of permutations.)

For example, the first sample test has N = 10, K = 4. • g = gcd(10, 4) = 2. Now, take N = 5 and K = 2.

• A = 3. We want to know: is the permutation (0, 3, 1, 4, 2) odd or even? In fact, for the second simplifying step, we need not calculate A; the answer will be the same if we consider (0, K, 2K mod N, 3K mod N, ..., (N − 1)K mod N). Hence, for the example above, it suffices to consider the permutation (0, 2, 4, 1, 3). This fact may seem puzzling at the moment; that it is true follows (though nontrivially) from the solution. Now, we have a transformed task at hand:

Given 1 ≤ K < N with gcd(N,K) = 1, is the permutation (0, K, 2K mod N, 3K mod N, ..., (N − 1)K mod N) odd or even?

Propositions will be stated without proof. Most of them are simple facts and it will be cumbersome to put down all the proofs here.

1 Special Case: N is an odd prime

We focus on the special case where N is an odd prime. First, we use the following proposition:

Proposition 1. An odd permutation becomes even after swapping two (not necessarily adjacent) elements, and vice versa.

Thus, we only need to consider the number of (not necessarily adjacent) swappings needed to sort the elements of the permutation.

An Example Consider the following example (N = 11, K = 8). The permutation is:

0 8 5 2 10 7 4 1 9 6 3

Discarding 0 (this will not affect the answer), we see that the elements are nicely split into two halves:

8 5 2 10 741963

Do you see the nice symmetry?

8+3 = 11 5+6 = 11 2+9 = 11 10+1 = 11 7+4 = 11

Therefore, if we swap the blue elements that are “too large” (i.e. larger than N/2) with the corresponding red elements, we obtain the following:

3 5 2 1 4 7 10 9 6 8

Three (3) swaps performed in total. Then, to sort the elements, we only need to perform swappings independently within the blue group and the red group. But the two groups are symmetric, so, for this stage, the total number of swappings must be even.

Counting Tricks Making use of this observation, we see that the parity of the number of swappings only depends on the number of “large” elements in the blue group. In other words, we need to count the number of solutions to the following simultaneous equations:

2 ( N 1 ≤ r ≤ 2 N rK mod N > 2 This is not easy to count, but there is a trick when N is an odd prime and when we are concerned only with the parity of the number of solutions. Let the sought number of solutions be s. We consider the product P1 of the blue elements.

N−1 P1 = K × (2K) × ... × ( 2 K) N−1 N−1 2 = ( 2 )! × K N−1 On the other hand, consider the product P2 of numbers from 1 to 2 .

N−1 P2 = ( 2 )! Observe that every time we swap a blue element with the corresponding red element, the value of P1 (the product of blue elements) modulo N mul- tiplies by (-1). (This is becauseX is replaced byN-X.) After swapping for s times, the product changes from P1 to P2. So we have:

s (−1) P1 ≡ P2 (mod N) N−1 s N−1 2 N−1 (−1) × ( 2 )! × K ≡ ( 2 )! (mod N) s N−1 (−1) ≡ K 2 (mod N)

N−1 To get from the second line to the last line, cancel ( 2 )! from both s N−1 sides, then multiply (−1) on both sides. Cancellation of the term ( 2 )! is valid because N is prime; without this condition, the last line does not follow.

N−1 Hence, we can find out whether s is odd or even by calculating K 2 mod N. If the value is 1, s is even. Otherwise, s is odd. This can be computed in O(log N) per query, using fast exponentiation.

Case 1: N is odd

Next, we generalise our work to arbitrary odd N. The case where N is even will be dealt with in the last section. Let N = pM, where p is an odd prime and M > 1 is odd. Write the N numbers in a rectangular array of size p × M (we omit mod N from the table so it would not look clumsy):

0 K 2K ... (M − 1)K MK (M + 1)K (M + 2)K ... (2M − 1)K ...... ((p − 1)M)K ((p − 1)M + 1)K ((p − 1)M + 2)K ... (N − 1)K

3 One can observe that numbers on the same column have the same value modulo M. This provides inspiration for the following swapping algorithm:

• Step 1: sort the elements in each column • Step 2: sort the columns “as a whole”

We demonstrate this two-step algorithm using the example N = 15, p = 3, M = 5, K = 7. First, we draw the 3 × 5 table:

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

Next, we sort the elements in each column.

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

Note that we perform no (0) swaps for column 1 and two (2) swaps for columns 2 through 5. It is not a coincidence that these number of swappings have the same parity; we state it as a proposition here.

Proposition 2. Let ui be the number of swappings required for column i. Then ui ≡ uj (mod 2).

Corollary. Let s be the number of swappings required for step 1. Then s p−1 (−1) ≡ K 2 (mod p)

From Proposition 2, it suffices to consider column 1. Dividing each element by M, we obtain, in order, the elements 0, K mod p, ..., (p − 1)K mod p. By previous analysis on the case where N is an odd prime, the corollary follows. Finally, we move on to step 2 and sort the columns.

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

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

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

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

Each time, we swap p pairs of elements. As p is odd, we may as well consider just the first row, which consists of 0, K mod M, 2K mod M, ..., (M − 1)K mod M. We have successfully reduced the problem from (N, K) to (M, K mod M).

Hence, we arrive at the following algorithm for the case where N is odd:

solve(N, K): // P = (0, K, 2K mod N, ..., (N − 1)K mod N) // returns 0 if P is even, 1 if P is odd if N = 1 return 0 p := odd prime dividing N res := f(K, p), b−1 where f(a, b) = a 2 mod b (take 1 or -1) if res = 1 N N return solve( p , K mod p ) else N N return 1 - solve( p , K mod p )

By induction, we can rewrite the above algorithm as follows:

solve2(N, K): // P = (0, K, 2K mod N, ..., (N − 1)K mod N) // returns 0 if P is even, 1 if P is odd factorise N := p1p2p3...pa, pi prime res := f(K,p1) f(K,p2) ... f(K,pa), b−1 where f(a, b) = a 2 mod b (take 1 or -1) if res = 1 return 0 else return 1

This algorithm depends heavily on the efficiency of prime factorisation. Also, we need fast exponentiation for calculating f(a, b). Therefore, the time complexity (per query) is FACT(N) + O(log N), where FACT() is the time complexity√ of the factorisation algorithm used. For example, if FACT(N) = O( N), it will be fast enough to solve all subtasks (at least for the cases where N is odd).

5 Case 2: N is even

Write N = 2M. There are two sub-cases to consider: M is odd and M is even.

Case 2.1: M is odd Write the 2M numbers in a M × 2 table, as follows (we omit mod N): 0 K 2K 3K 4K 5K ...... (2M − 2)K (2M − 1)K The numbers on the first column are all even and those on the second column are all odd, so we do not need to swap elements on the first column with those on the second column. Again, as M is odd, the number of swaps required to sort the first column is congruent to that to sort the second column, modulo 2 (recall Proposition 2).

Therefore, when N ≡ 2 (mod 4), the permutation is always even.

Case 2.2: M is even Similar to the sub-case above, we write the numbers in a M × 2 table: 0 K 2K 3K 4K 5K ...... (N − 2)K (N − 1)K Our aim to to rearrange the second column so that each element on the second column is exactly (1 + its left element), after which the table will be symmetric and the additional number of swaps will be even.

For example, if N = 12 and K = 5, we initially have the table on the left and we wish to achieve the table on the right.

0 5 0 1 10 3 10 11 8 1 8 9 6 11 6 7 4 9 4 5 2 7 2 3

6 Notice that it can be done by cyclic shifting the whole column by a certain number of steps. How many steps, you ask? It will become obvious after we colour some cells.

0 5 10 3 8 1 6 11 4 9 2 7

Each shifting, we swap (M − 1) pairs of elements, and the green and red cells interchange positions. In the final configuration, 1, which is green, is on the top-right corner. Notice that originally K is the number on the top-right corner. Therefore, if K is green, the number of swaps is odd; conversely, if K is red, the number of swaps is even.

How exactly are the colours determined? It is deceptively simple:

• we colour a number X green if X ≡ 1 (mod 4)

• we colour a number X red if X ≡ 3 (mod 4)

Therefore, we have the following: if K ≡ 1 (mod 4), the permutation is even. Otherwise, the permutation is odd.

Combining the two cases, the problem is solved.

7 Footnote

Now we have solved the problem, but two questions remain:

1. Can we solve it more efficiently?

2. How did the author come up with such a (insert adjective) problem?

The answer to the first question is an emphatic YES. In fact, the two questions are somewhat related, so I will answer them both at once.

The author came up with this problem while attending a number the- ory lecture, which back then was exploring a great result called “quadratic reciprocity” (QR). One proof of QR uses Gauss’s lemma, and after a bit googling you will see its connection with this problem, for the case where N is an odd prime. (To be more precise, Gauss’s lemma relates the quantity N−1 K 2 mod N to the number of elements in the first part with value larger N−1 than 2 .)

N−1 In fact, when N is an odd prime, K 2 (mod N) is exactly the Legendre K symbol ( N ), and Jacobi symbol, a generalisation of the Legendre symbol, corresponds exactly to our sought answer when N is odd (but not necessar- a ily prime)! Since the calculation of the Jacobi symbol ( b ) can be done in O(log b) time (it is, in some sense, similar to the Euclidean algorithm), and that the case when N is even can be solved in O(1) time, our problem can thus be solved in O(log N) time per query.

Don’t worry if you find this problem intimidating. This problem ap- pears in Mini-Comp 0 for the sole reason that it is not suitable for other contests. In particular, we would not test “advanced” number theory/pure mathematics/difficult pattern-finding in the Team Formation Test.

8