#!/usr/bin/env python3 import sys def expand(dense): fs = [] for i in range(len(dense)): if i % 2 == 0: for j in range(int(dense[i])): fs.append(i // 2) else: for j in range(int(dense[i])): fs.append(None) return fs def pprint(fs): for c in fs: if c is not None: print(c, end="") else: print(".", end="") print("") def compact(fs): comp = [c for c in fs] # First store the free space to avoid rescanning every time free = {} start = None size = 0 for i in range(len(comp)): if comp[i] is not None: if start is not None: free[start] = size start = None size = 0 else: if start is None: start = i size += 1 # work backwards id = comp[-1] end = len(comp) - 1 for i in range(len(comp) - 1, -1, -1): if comp[i] == id: # still in file block continue else: if id is not None: # span from i + 1 -> end needs moving start = i + 1 size = end - start + 1 for f in sorted(free.keys()): if f < start and free[f] >= size: # copy the block for j in range(size): comp[f + j] = comp[start + j] comp[start + j] = None # update our space free[f + size] = free[f] - size del(free[f]) break # reset state id = comp[i] end = i return comp def chksum(fs): tot = 0 for i in range(len(fs)): if fs[i] is None: continue tot += fs[i] * i return tot if __name__ == '__main__': dense = next(sys.stdin).strip() fs = expand(dense) comp = compact(fs) # pprint(comp) print(chksum(comp))