Approach
Sorting and greedy selection
For CCC 2015 S5 - Greedy for Pies, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 181 lines of Python from the credited upstream file ccc15s5.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 94 95file = open('s5.15.in')96N = int(file.readline())97L = [int(file.readline()) for n in range(N)] + [0] 98P = int(file.readline())99A = [int(file.readline()) for m in range(P)] 100A.sort()101 102103104105106107108 109110s5 = 1111s4 = 2*s5112s3 = (P+1)*s4113s2 = (P+1)*s3114s1 = (N+1)*s2115 116117s = [0]*(2*s1)118 119120s[0] = L[0]121if P != 0:122 s[1] = A[-1]123 124125for n in range(N+1):126 for m in range(min(n+1, P)+1):127 for M in range(min(n+1, P)+1-m):128 129 130 max_i = 0131 max_e = 0132 133 134 if m > 0:135 max_i = s[1*s1 + n*s2 + (m-1)*s3 + M*s4 + 1]136 max_e = s[1*s1 + n*s2 + (m-1)*s3 + M*s4 + 1]137 if M > 0:138 max_e = max(s[n*s2 + m*s3 + (M-1)*s4 + 1], max_e)139 140 if M+m != n+1 and n > 0:141 max_i = max(s[1*s1 + (n-1)*s2 + m*s3 + M*s4], max_i)142 max_e = max(s[1*s1 + (n-1)*s2 + m*s3 + M*s4], s[(n-1)*s2 + m*s3 + M*s4], max_e)143 144 s[n*s2 + m*s3 + M*s4] = max_i + L[n]145 146 s[1*s1 + n*s2 + m*s3 + M*s4] = max_e147 148 if M+m != P and M+m != n+1 and n > 0:149 150 151 152 153 max_i = s[1*s1 + (n-1)*s2 + m*s3 + M*s4]154 max_e = max(s[1*s1 + (n-1)*s2 + m*s3 + M*s4], s[(n-1)*s2 + m*s3 + M*s4])155 s[n*s2 + m*s3 + M*s4 + 1] = max_i + A[-M-1]156 s[1*s1 + n*s2 + m*s3 + M*s4 + 1] = max_e157 158159final_max = 0160for m in range(min(N+1, P)+1):161 for M in range(min(N+1, P)+1-m):162 163 if M == 0:164 rA = A[m:]165 else:166 rA = A[m:-M]167 final_max = max(final_max,168 s[1*s1+(N-1)*s2+m*s3+M*s4] + sum(rA[len(rA)2:]),169 s[(N-1)*s2+m*s3+M*s4] + sum(rA[-((-len(rA))2):]))170 171 if M+m != P or M+m != N+1:172 if M == 0:173 rA = A[m+1:]174 else:175 rA = A[m+1:-M]176 final_max = max(final_max, s[1*s1+n*s2+m*s3+M*s4+1] + sum(rA[len(rA)2:]))177 rA = A[m:-M-1]178 final_max = max(final_max, s[n*s2+m*s3+M*s4+1] + sum(rA[-((-len(rA))2):]))179 180print(final_max)181