Computing competitions

2026 Southeast Regional Solutions

On this page

Each section connects a selected contest problem to its algorithm, explains why the algorithm works, and includes the provided Python implementation. Follow the Kattis link for the complete statement, input format, and constraints.

Problem A — What Really Is ICPC?

Open the original problem on Kattis .

Goal. Four words are proposed as an expansion of the acronym ICPC. Determine whether their first letters, read in the given order, form that acronym.

From the problem to the algorithm. An acronym depends only on the first character of each word. The remaining letters can be ignored, even when their capitalization looks unusual. The input guarantees four words with uppercase first letters, so splitting the line on whitespace gives exactly the pieces we need.

Build the list of initials and compare it with ['I', 'C', 'P', 'C']. Order matters: having the right letters somewhere among the four words is insufficient. There is also no need to check whether the words are the official expansion of ICPC; any words with those initials satisfy the condition.

Example. The official first sample, International Collegiate Programming Contest, produces I, C, P, C, so the answer is 1. In Undergraduate Competitive Programming Club, the first initial is U, so the answer is 0.

Why it works. The program extracts exactly the characters used to define the acronym. The list comparison succeeds precisely when all four initials match the required letters in their required positions.

Complexity. Let $L$ be the total input length. Splitting the input takes $O(L)$ time and space; extracting and comparing four initials takes constant time.

Python solution.

words = input().split()

fl = [word[0] for word in words]
print(1 if fl == list("ICPC") else 0)

Problem B — Castle-pult

Open the original problem on Kattis .

Goal. Three castles lie on a circle with $n$ equally spaced zones. Each castle must launch its troops exactly $x$ zones clockwise or counterclockwise before they walk to another castle. The launch is free, walking costs one day per zone, and every castle must use the same positive integer $x$. Choose $x$ to minimize the longest travel time between any pair of castles. Output that minimum travel time, rather than the launch distance itself.

First reduce the geometry. For positions $a$ and $b$, let $\delta=|a-b|$. Walking around the circle gives two possible distances, so their shortest separation is

$$ d=\min(\delta,n-\delta). $$

There are only three pairs of castles, so compute these three values. Each lies between $1$ and $\lfloor n/2\rfloor$.

What does the cannon change? A launch length can be reduced modulo $n$, and choosing between clockwise and counterclockwise makes launch lengths $x$ and $n-x$ equivalent. We can therefore reason about a normalized launch length $y$ between $0$ and $\lfloor n/2\rfloor$.

For a pair with shortest separation $d$, the best launch leaves $|d-y|$ zones to walk. If $y<d$, launch along the shorter arc and walk the remaining distance. If $y>d$, overshoot along that arc and walk back. Launching the other way cannot improve this: its possible walking distances are $d+y$ and $n-d-y$, both at least $|d-y|$ because $d,y\le n/2$.

Choose one launch distance for every pair. Let $\ell$ and $h$ be the smallest and largest of the three separations. We want to minimize

$$ \max_i |d_i-y|=\max(|\ell-y|,|h-y|). $$

For any choice of $y$, covering the gap from $\ell$ to $h$ requires a worst error of at least $\lceil(h-\ell)/2\rceil$. Choosing an integer nearest their midpoint achieves that bound. All intermediate separations lie within the same interval and introduce no larger error. The midpoint is a valid positive launch length because all three separations are positive.

Thus the answer is

$$ \left\lceil\frac{h-\ell}{2}\right\rceil, $$

which is exactly (max(distances) - min(distances) + 1) // 2 in the code.

Example. For the official sample 11 1 4 9, the three shortest separations are $3$, $3$, and $5$. Launching $4$ zones leaves at most one zone to walk, so the answer is $1$.

Complexity. Three pairwise calculations take $O(1)$ time and space, even when $n$ is very large.

Python solution.

n, *positions = map(int, input().split())

distances = []
for i in range(3):
    for j in range(i + 1, 3):
        delta = abs(positions[i] - positions[j])
        distances.append(min(delta, n - delta))

print((max(distances) - min(distances) + 1) // 2)

Problem C — Crystalline Creation

Open the original problem on Kattis .

Goal. Recreate a target grid of crystals, initially starting with an empty grid. You may place a crystal manually, grow one immediately above the highest crystal in a column, or grow one immediately left of the leftmost crystal in a row. Minimize the number of manual placements. Crystals cannot be removed, so growing a crystal into a target . cell would make the result invalid.

Reason backward from a target crystal. A crystal at row $i$, column $j$ can be grown only from a crystal immediately below it or immediately to its right. If both of those neighboring positions are either outside the grid or . in the target, neither growth method can create this crystal. It must be placed manually.

This gives a necessary count: count every * that has no * directly below and no * directly to its right. Notice that both neighbors must be absent for a manual placement to be forced. One useful neighbor is enough to avoid that placement.

Why this count is also sufficient. The rules mention the highest crystal in a column and the leftmost crystal in a row, so we must show that other crystals will not block the proposed growth. Imagine constructing the target from the bottom row upward, and within each row from right to left:

  1. When processing a target *, its below and right neighbors have already been processed.
  2. If the below neighbor is *, it is currently the highest existing crystal in that column: all rows above it are still unprocessed. Shining on the column creates the current crystal.
  3. Otherwise, if the right neighbor is *, it is the leftmost existing crystal in this row: the cells farther left are still unprocessed. Shining on the row creates the current crystal.
  4. If neither neighbor is *, place the current crystal manually.

Every added crystal belongs in the target, and manual placement is used only for the cells already shown to require it. This construction matches the lower bound, so the count is optimal. The program only needs to count these cells; it does not need to simulate the construction order.

Example. In the first official sample, the top horizontal run needs one manual crystal at its right end. The lower group needs one at its bottom end, from which the remaining crystals can grow upward and leftward. The answer is $2$.

Connection to the code. For a *, the if condition asks whether either supporting neighbor exists. If so, the program skips it; otherwise it increments the answer. Bounds checks make a neighbor outside the grid behave like an absent crystal.

Complexity. Scanning all $rc$ cells takes $O(rc)$ time. The stored grid uses $O(rc)$ space, and the counting logic uses $O(1)$ additional space.

Python solution.

r, c = map(int, input().split())
rows = [input() for _ in range(r)]

count = 0
for i in range(r):
    for j in range(c):
        if rows[i][j] == "*":
            if (i + 1 < r and rows[i + 1][j] == "*") or (j + 1 < c and rows[i][j + 1] == "*"):
                continue
            else:
                count += 1
print(count)

Problem D — Split the Bill

Open the original problem on Kattis .

Goal. A group of friends splits each meal’s bill using whole dollars. Within one meal, no two payments may differ by more than one dollar. Different friends may pay the extra dollars at different meals. Decide whether everyone can finish with the same total payment across all meals.

Separate a bill into equal payments and extras. For $p$ friends, write a bill as

$$ c_i=pq_i+r_i,\qquad 0\le r_i<p. $$

Everyone pays the base amount $q_i$. Exactly $r_i$ distinct friends pay one additional dollar. The base amounts are already equal for everyone, so only the allocation of these extras matters.

A necessary condition. If everyone pays the same integer total, the sum of all bills must be divisible by $p$. A nonzero remainder makes equal final totals impossible.

Why divisibility is sufficient. Line up the friends in a circle and distribute the extra dollars in cyclic order, continuing from where the previous meal stopped. A meal has fewer than $p$ extras, so this assigns at most one extra dollar to any friend for that meal and obeys the payment rule. If the total bill is divisible by $p$, then $\sum_i r_i$ is also divisible by $p$. The extra assignments complete a whole number of cycles, giving every friend the same number of extras.

This proves that checking the grand total is enough. We do not need to search over who pays extra at each meal, and individual bills do not all have to be divisible by the group size.

Example. The first official sample has $5$ friends and bills $17$, $3$, and $15$. Everyone’s base payments total $3+0+3=6$ dollars. The meals require $2+3+0=5$ extras altogether, which can give one extra to each friend. Everyone pays $7$ dollars, so the answer is 1.

Complexity. Summing $m$ bills takes $O(m)$ time. The provided implementation stores the bills in a list, using $O(m)$ space; a running sum could use $O(1)$ additional space.

Python solution.

p, m = map(int, input().split())

c = [int(input()) for _ in range(m)]

print(1 if sum(c) % p == 0 else 0)

Problem E — Painted Maze

Open the original problem on Kattis .

Goal. Reach the bottom-right cell from the top-left cell of a colored grid. A 0 is an obstacle. You may step to a side-adjacent non-obstacle cell for cost $0$ if the color stays the same or cost $1$ if it changes. From a cell of a designated special color, you may also teleport to any other cell of that color for free. Find the minimum total cost, or report -1 if the destination is unreachable.

Recognize the shortest-path problem. Treat each usable cell as a graph vertex. Walking and teleporting provide edges, and the edge weights are either $0$ or $1$. We minimize the sum of edge costs, so the path with the fewest moves need not be best: many free moves can be preferable to one color change. Ordinary BFS, which treats every move equally, would optimize the wrong quantity.

Use 0–1 BFS. This is Dijkstra’s shortest-path idea specialized to weights $0$ and $1$. A deque holds cells waiting to be processed. When relaxing an edge from a cell at distance $d$:

  • a zero-cost improvement has distance $d$, so add it to the front;
  • a one-cost improvement has distance $d+1$, so add it to the back.

This keeps the search in increasing distance order. A cell’s distance is final when it is first processed. The done array skips duplicate queue entries, and this ordering makes it safe to stop as soon as the destination is processed.

Avoid building every teleport edge. If $t$ cells share one special color, explicitly connecting every pair would require $O(t^2)$ edges. Instead, group their indices in a list for that color. When the search first processes a cell of this color at distance $d$, relax every member of its group to distance $d$.

That group never needs to be scanned again. The first processed member has the minimum distance among all members, and free teleportation already gives every other member that distance. Reaching the color again cannot improve those teleport distances. teleports.pop(color, ()) both retrieves and removes the list, enforcing this rule.

How the implementation represents the grid. Use row and column indices starting from $0$, and flatten the grid so cell $(i,j)$ has index $i\cdot\text{cols}+j$. Up and down differ by cols; left and right differ by $1$. The column checks prevent a horizontal move from accidentally wrapping from one row into the next. Neighboring obstacle cells are skipped. dist[0] = 0 initializes the source; all other distances start above any possible shortest simple path’s cost.

Example. In the first official sample, walk through color $1$ to cell $(1,3)$ of color $2$, paying $1$ for that color change. Teleport to $(3,5)$, also color $2$, for free. Step to $(3,6)$ of color $4$, paying another $1$, then continue to $(4,6)$ for free. The total is $2$. Coordinates here use the statement’s numbering from $1$.

Why it works. Every allowed move is represented by an edge with its correct cost. The deque processes distance improvements in the order required by 0–1 BFS. Scanning a teleport group once preserves all useful free connections, so the optimization does not discard a better route. If the deque empties without reaching the destination, no allowed path reaches it.

Complexity. Let $N=rc$. Each cell has at most four walking neighbors, and each special-color list is scanned at most once. Total time and space are $O(N)$, including the stored grid, distances, deque, and color groups.

Python solution.

import sys
from collections import deque

data = list(map(int, sys.stdin.buffer.read().split()))
rows, cols, k, s = data[:4]
n = rows * cols
grid = data[4:4 + n]

teleports = {color: [] for color in data[4 + n:]}
for cell, color in enumerate(grid):
    if color in teleports:
        teleports[color].append(cell)
del data

dist = [n + 1] * n
dist[0] = 0
done = bytearray(n)
queue = deque([0])

while queue:
    cell = queue.popleft()
    if done[cell]:
        continue
    done[cell] = 1

    if cell == n - 1:
        print(dist[cell])
        exit()

    current_dist = dist[cell]
    color = grid[cell]

    # Expand each special color only once.
    for nxt in teleports.pop(color, ()):
        if current_dist < dist[nxt]:
            dist[nxt] = current_dist
            queue.appendleft(nxt)

    neighbors = []
    if cell >= cols:
        neighbors.append(cell - cols)
    if cell + cols < n:
        neighbors.append(cell + cols)

    column = cell % cols
    if column > 0:
        neighbors.append(cell - 1)
    if column + 1 < cols:
        neighbors.append(cell + 1)

    for nxt in neighbors:
        if grid[nxt] == 0:
            continue

        weight = int(grid[nxt] != color)
        new_dist = current_dist + weight

        if new_dist < dist[nxt]:
            dist[nxt] = new_dist
            if weight == 0:
                queue.appendleft(nxt)
            else:
                queue.append(nxt)

print(-1)

Problem F — Fork It Over

Open the original problem on Kattis .

Goal. Each day an office receives some utensil bags and needs one bag per person eating lunch. Extra bags go into an unlimited reserve. A shortage first uses the reserve; any remaining shortage must be bought from a store immediately. The reserve starts empty. Find the total number of bags bought over all days.

Choose the state that connects one day to the next. Past days matter only through the unused bags left in the reserve. Keep store for this reserve and purchase for the cumulative number bought. For a day with $b$ delivered bags and $p$ people, there are store + b bags available before buying anything.

If this covers the people, subtract $p$ and carry the remainder forward. Otherwise, the missing amount is p - store - b; add that amount to purchase and set the reserve to zero. Purchased bags are all used immediately, so they never increase the reserve.

Why the days must stay in order. Later deliveries cannot supply an earlier lunch. Subtracting total people from total deliveries loses this timing information and can underestimate the purchases.

Example. The official sample evolves as follows:

Day Delivered People Bought that day Reserve afterward
1 2 4 2 0
2 5 1 0 4
3 3 3 0 4
4 1 6 1 0
5 4 2 0 2

The answer is $3$, even though the total deliveries fall short of the total demand by only $1$ bag. Two bags arrive too late to offset the earlier purchases and remain in reserve.

Why it works. Before each day, store is exactly the number of unused bags from previous deliveries. The update uses all currently available bags and buys precisely the uncovered demand, as the rules require. This maintains the invariant for the next day and records every purchase exactly once.

Complexity. The simulation takes $O(n)$ time and $O(1)$ additional space.

Python solution.

n = int(input())
store = 0
purchase = 0
for i in range(n):
    b, p = map(int, input().split())
    if store + b < p:
        purchase += p - store - b
        store = 0
    else:
        store = store + b - p

print(purchase)

Problem G — Guaranteed Drop

Open the original problem on Kattis .

Goal. Buy containers until one drops a desired ship. A container type has price $p$, ordinary success probability $r$, and a guarantee $g$: if its first $g-1$ openings fail, its $g$-th opening must succeed. Guarantees are tracked separately for each type. The problem permits switching types before each purchase and asks for the smallest expected total cost.

Compute the cost of committing to one type. Let $q=1-r$ be the failure probability. You always pay for the first container. You pay for a second only if the first fails, for a third only if the first two fail, and so on. No more than $g$ containers are needed. Therefore,

$$ C_g=p+pq+pq^2+\cdots+pq^{g-1}. $$

Here $p$ is the cost per purchase, and $g$ is the purchase count at which that type guarantees success.

We can evaluate this finite sum without exponentiation. Define $C_0=0$ and build

$$ C_t=p+qC_{t-1},\qquad t=1,\ldots,g. $$

For $t=1$, this gives $C_1=p$, the price of a guaranteed final container. For larger $t$, pay $p$ now and incur the remaining expected cost only on failure. The loop builds the expected cost from the guaranteed last purchase back to the first purchase.

Why is taking the best single type enough? Switching is allowed, so this needs justification. At any point, let $C_i$ be the expected additional cost of using only type $i$ from then on. A failed opening moves that type closer to its guarantee, so its remaining cost decreases; the costs of untouched types stay the same.

A more precise argument shows that mixing cannot beat $M=\min_i C_i$. Use induction on the total number of failures still possible before the guarantees. If no failures remain, every next purchase guarantees success and the cheapest one is optimal. A failed purchase reduces the remaining failure count by one, so the same claim can be assumed for the state reached after that failure.

Suppose the next purchase is a non-guaranteed container of type $j$. Let $C’_j$ be its remaining committed cost after failure, and let $B$ be the smallest committed cost among the other types. With no other type, take $B=+\infty$. The induction hypothesis makes the best continuation cost $\min(C’_j,B)$.

  • If $C’_j\le B$, the best continuation after failure costs $C’_j$. Buying this container and continuing has expectation $p_j+q_jC’_j=C_j\ge M$.
  • If $B<C’_j$, switching to another type after failure gives expectation $p_j+q_jB$. Since $C’_j$ is a finite geometric sum, $C’_j\le p_j/r_j$. Thus $B<p_j/r_j$ and $p_j+q_jB\ge B\ge M$.

A guaranteed next purchase costs $p_j=C_j\ge M$ as well. This argument applies recursively after failures: there are only finitely many possible failures before some guarantee forces success. It proves that no first choice and continuation can do better than $M$.

Choosing the type that attains $M$ and committing to it achieves $M$. After any failure, that type’s remaining committed cost becomes smaller, so there is no reason to switch. The algorithm can therefore evaluate each type independently and take the minimum.

Example. In the first official sample, $p=5$, $r=0.5$, and $g=3$. The expected payment is $5+0.5\cdot5+0.25\cdot5=8.75$ coins. The third term is paid only when the first two openings both fail.

Complexity. The recurrence takes $O(g_i)$ work for type $i$, giving $O(\sum_i g_i)$ time and $O(1)$ additional space. With at most $1{,}000$ types and $g_i\le100$, this is small. Floating-point arithmetic and twelve digits after the decimal point provide the precision requested by the statement.

Python solution.

import sys
input = sys.stdin.buffer.readline
n = int(input())

answer = float("inf")

for _ in range(n):
    p, r, g = input().split()
    p = int(p)
    q = 1.0 - float(r)
    g = int(g)

    expected = 0.0
    for _ in range(g):
        expected = p + q * expected

    answer = min(answer, expected)

print(f"{answer:.12f}")

Problem I — Feelin’ Lucky?

Open the original problem on Kattis .

Goal. A slot machine has four reels. Each reel may stop on any of its listed letters, and the machine may rearrange the reels. Decide whether some arrangement and choice of letters can display ICPC. We need to determine whether winning is possible, rather than calculate its probability.

Turn reel shuffling into a small assignment search. To win, the four reels must collectively supply one I, one P, and two Cs, with each reel supplying exactly one letter. Instead of explicitly permuting the reels, keep the input reels in place and permute the letters we ask them to supply.

For a candidate permutation, check whether its first letter exists on the first input reel, its second letter on the second reel, and so on. If all four checks pass, those chosen letters can be rearranged with their reels into ICPC.

Handle the repeated letter. ICPC has two copies of C, so it has $4!/2!=12$ distinct permutations. itertools.permutations generates $24$ positional permutations, and the set removes the duplicates. Sorting only gives a consistent iteration order; it is not needed for correctness.

It is insufficient to check whether all required letters appear somewhere among the reels. Two distinct reels must supply the two Cs, and using one reel for I prevents using that same reel for P or C.

Why the search is complete. If a checked permutation succeeds, each input reel can supply its assigned letter, and the reels can then be put into the winning order. Conversely, any winning spin assigns the multiset of letters I, C, P, C to the original four reels. That assignment is one of the twelve candidates, so the algorithm will find it.

The code stops at the first successful assignment and prints 1. If every assignment fails, it prints 0.

Complexity. Let $L$ be the length of a reel’s letter list. The program tests $12$ distinct assignments with four string-membership checks each, taking $O(L)$ time because the number of reels and assignments is fixed. Reading the four reels uses $O(L)$ space; the permutation collection has constant size.

Python solution.

import itertools

lines = [input() for _ in range(4)]

s = "ICPC"
unique_permutations = sorted(set("".join(p) for p in itertools.permutations(s)))
result = 0
for perm in unique_permutations:
    match = True
    for i, line in enumerate(lines):
        if perm[i] not in line:
            match = False
            break
    if match:
        result = 1
        break
print(result)

Problem J — Snow Many Ways

Open the original problem on Kattis .

Goal. A snowflake begins with one unfrozen crystal. In an expansion, every currently unfrozen crystal becomes frozen and produces $x>1$ new unfrozen crystals. The multiplier $x$ is the same within one expansion but may change between expansions. Among processes ending with exactly $u$ unfrozen crystals, maximize the total number of frozen crystals.

Express a process as factors. If the expansion multipliers are $x_1,x_2,\ldots,x_t$, the final unfrozen count is their product:

$$ u=x_1x_2\cdots x_t. $$

The frozen crystals created at each expansion are the unfrozen crystals that existed immediately before it. Their total is

$$ 1+x_1+x_1x_2+\cdots+x_1x_2\cdots x_{t-1}. $$

This turns the growth story into a factorization and ordering problem.

Use prime multipliers. Suppose one expansion multiplies by a composite number $ab$, with $a,b>1$, and there are $M$ unfrozen crystals before it. The single expansion adds $M$ frozen crystals. Splitting it into an expansion by $a$ followed by one by $b$ adds $M+Ma$ frozen crystals and ends with the same $Mab$ unfrozen crystals. The extra $Ma$ is positive. Therefore, an optimal process splits every composite multiplier until all multipliers are prime.

Put larger primes first. Compare two neighboring multipliers $a$ and $b$, starting from $M$ unfrozen crystals. Their frozen contribution is $M+Ma$ in the order $a,b$, or $M+Mb$ in the order $b,a$. Everything after them sees the same $Mab$ unfrozen crystals. Thus putting the larger multiplier first never decreases the answer. Repeated swaps give the optimal order: prime factors from largest to smallest.

Why does the code divide out the smallest primes first? It reconstructs that optimal process backward. Start from the final count $u$. The last forward multiplier is the smallest remaining prime $p$, so before that expansion there were $u/p$ unfrozen crystals. Those are exactly the crystals frozen by the last expansion: divide by $p$ and add the quotient. Repeat to account for the preceding expansions in reverse order.

Repeated prime factors must be removed one at a time because each occurrence represents a separate expansion. Once trial division finishes, a remaining value greater than $1$ is prime. Removing this last factor would leave the original single crystal, so it contributes $1$.

Example. For the official sample $u=6$, expand first by $3$ and then by $2$. The two expansions freeze $1$ and $3$ crystals, for a total of $4$. Reversing the multipliers would freeze only $1+2=3$, and using a single multiplier of $6$ would freeze only $1$. The code divides $6$ by $2$, adds $3$, then accounts for the remaining prime factor by adding $1$.

Complexity. Trial division takes $O(\sqrt{u})$ time in the worst case and $O(1)$ additional space. As factors are removed, the remaining value shrinks, so the loop can stop when p * p > n.

Python solution.

n = int(input())
answer = 0
p = 2

while p * p <= n:
    while n % p == 0:
        n //= p
        answer += n

    p += 1

if n > 1:
    answer += 1

print(answer)

Problem L — Volleyball Scoring

Open the original problem on Kattis .

Goal. Each rally gives one point to its winner, who serves next. Before a serve, the caller announces only the last digits of the scores, with the serving team’s digit first. The input gives the current server’s score $a$ and the receiver’s score $b$. Find the fewest future rallies needed to hear 6 7. Play has no winning-score limit.

The order of the call matters. Reaching score digits $6$ and $7$ is not enough by itself: the team whose score ends in $6$ must be serving. For any positive number of future rallies, that team must win the final rally. This is the detail that creates the positive-increment checks in the code.

If the current call is already 6 7, the answer is $0$. Otherwise, consider which of the two original teams serves at the end.

Case 1: the original serving team serves at the end. Its score must end in $6$, and it must score at least once so it can win the final rally. The smallest positive number of points it needs is (6 - a) % 10, except that a result of zero must become $10$. The other team’s score must end in $7$, and it is allowed to score zero points, so it needs (7 - b) % 10 points. Adding these gives first.

Case 2: the original receiving team serves at the end. Now that team’s score must end in $6$ and increase by at least one. Its required points are (6 - b) % 10, again replacing zero with $10$. The original server needs (7 - a) % 10 points, possibly zero. Their sum is second.

Why these totals are achievable and optimal. In either case, every required point needs one rally, so the sum is a lower bound. It is also achievable: let the eventual receiver win all the rallies it needs, then let the eventual server win its required rallies. The latter has a positive point count, so it wins the final rally and serves next. These two cases cover every possible final server; take their minimum.

Example. In the official sample with scores 6 6, giving one point to the receiver makes that team serve with digit $7$, so the call is 7 6. To finish with the original server serving at digit $6$, it must gain $10$ points, while the other team gains $1$ to reach digit $7$. That takes $11$ rallies. Choosing the other final server also takes $11$, so the answer is $11$.

Complexity. A fixed number of modular-arithmetic operations takes $O(1)$ time and space.

Python solution.

a, b = map(int, input().split())

if a % 10 == 6 and b % 10 == 7:
    print(0)
    exit()

a_to_six = (6 - a) % 10
if a_to_six == 0:
    a_to_six = 10

b_to_six = (6 - b) % 10
if b_to_six == 0:
    b_to_six = 10

first = a_to_six + (7 - b) % 10
second = (7 - a) % 10 + b_to_six

print(min(first, second))

Back to the contest

2026 Southeast Regional Contest · 2025 Southeast Regional Contest