Problem solution · Python

CCC 2020 S4 - Swapping Seats

CCC 2020 S4 - Swapping Seats: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Direct simulation
Source
CCCSolutions
Length
38 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For CCC 2020 S4 - Swapping Seats, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 38 lines of Python from the credited upstream file ccc20s4.py.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2020 S4 - Swapping Seats · PythonPython
Use this to learn the idea, then write your own version.
# Daniel Zhang, Pinetree Secondary School  import sys  s = sys.stdin.readline().rstrip().lower()n = len(s)*2 counts = {'a':0, 'b':0, 'c':0}for c in s:    counts[c] += 1 S = s + s #psa setuppsa = {'a':[0]*(n+1), 'b':[0]*(n+1), 'c':[0]*(n+1)}for i in range(1, n+1):    psa['a'][i], psa['b'][i], psa['c'][i] = psa['a'][i-1], psa['b'][i-1], psa['c'][i-1]    psa[S[i-1]][i] += 1 ans = 999999999for o in ['abc', 'acb']:    f, s, t = o[0], o[1], o[2]    #print(o, counts)    for i in range(n//2):        f_section_end = i + counts[f] #exclusive        s_section_end = i + counts[f] + counts[s] #exclusive        t_section_end = i + counts[f] + counts[s] + counts[t] #        #print(f_section_end, s_section_end, t_section_end, "i:", i,end=" fins, sinf :")        num_s_in_f = psa[s][f_section_end] - psa[s][i] #number of the second letter in the first section        num_f_in_s = psa[f][s_section_end] - psa[f][f_section_end] #number of the first letter in second section        num_not_t_in_t = counts[t] - (psa[t][t_section_end] - psa[t][s_section_end])         ans = min(ans, num_not_t_in_t + max(num_f_in_s, num_s_in_f))  print(ans)

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗