"""Construct a block with large subset-sum support using the rank covers.""" from argparse import ArgumentParser from fractions import Fraction from heapq import heapify, heappop, heappush from itertools import combinations, groupby, product from math import comb, prod import json def masks_of_size(n, j): for positions in combinations(range(n), j): yield sum(1 << i for i in positions) def local_cover(n, j, u): """Greedily cover all local j-sets by local u-sets.""" remaining = list(masks_of_size(n, j)) selected = [] while remaining: chosen = 0 for i in range(n): tail = n - i - 1 prefix = (1 << (i+1)) - 1 options = [] for choice in (chosen, chosen | (1 << i)): take = u - choice.bit_count() if not 0 <= take <= tail: continue score = 0 for member in remaining: if member & prefix & ~choice: continue missing = (member >> (i+1)).bit_count() if missing <= take: score += comb(tail-missing, take-missing) options.append((Fraction(score, comb(tail, take)), -choice)) chosen = -max(options)[1] remaining = [member for member in remaining if member & ~chosen] selected.append(chosen) return selected def profiles(sizes, total): for entry in product(*(range(n+1) for n in sizes)): if sum(entry) == total: yield entry def rank_cover(k, u): """Cover the middle layer. Incidence counting also covers every lower rank.""" j = k // 2 sizes = [k//4 + (i < k%4) for i in range(4)] offsets = [sum(sizes[:i]) for i in range(4)] for ranks in profiles(sizes, j): def score(widths): if any(t > w for t, w in zip(ranks, widths)): return Fraction(0) return prod(Fraction(comb(w,t), comb(n,t)) for n,t,w in zip(sizes,ranks,widths)) widths = max(profiles(sizes, u), key=score) local = [local_cover(n,t,w) for n,t,w in zip(sizes,ranks,widths)] for parts in product(*local): yield sum(part << pos for part,pos in zip(parts,offsets)) def ordered_sums(weights): """Stream exact sums with their indexed masks, including ties.""" def subset_sums(items, start): totals = [(0, 0)] for i, w in enumerate(items, start=start): bit = 1 << i totals += [(value + w, mask | bit) for value, mask in totals] return sorted(totals) mid = len(weights)//2 left = subset_sums(weights[:mid], 0) right = subset_sums(weights[mid:], mid) heap = [(value + right[0][0], i, 0) for i, (value, _) in enumerate(left)] heapify(heap) while heap: value, row, col = heappop(heap) yield value, left[row][1] | right[col][1] col += 1 if col < len(right): heappush(heap, (left[row][0] + right[col][0], row, col)) def support_size(weights): return sum(1 for _ in groupby(ordered_sums(weights), key=lambda pair: pair[0])) def deletion_supports(weights): """Count every one-coordinate restriction in a single pass.""" full = (1 << len(weights)) - 1 counts = [0] * len(weights) for _, group in groupby(ordered_sums(weights), key=lambda pair: pair[0]): mandatory = full for _, mask in group: mandatory &= mask for i in range(len(weights)): counts[i] += not (mandatory & (1 << i)) return counts def reserve_supports(weights, reserve): """Count supports for the base and all prefixes of the ordered reserve.""" offset = len(weights) histogram = [0] * (len(reserve) + 1) records = ordered_sums([*weights, *reserve]) for _, group in groupby(records, key=lambda pair: pair[0]): first = min((mask >> offset).bit_length() for _, mask in group) histogram[first] += 1 for i in range(1, len(histogram)): histogram[i] += histogram[i - 1] return histogram def reserve_representatives(base_width, supports, step): """Use the last reserve prefix in each bin of integer deficiencies.""" if step < 1: raise ValueError("The bin width must be positive.") longest = {} for length, count in enumerate(supports): deficiency = base_width + length + 1 - count.bit_length() longest[deficiency // step] = length return tuple(longest.values()) def extract(weights, u): k = len(weights) if not 0 <= u <= k: raise ValueError('The retained size must be between zero and the block size.') if u < k//2: candidates = masks_of_size(k,u) else: candidates = rank_cover(k,u) best_count, best_mask = 0, 0 for mask in candidates: size = support_size([w for i,w in enumerate(weights) if mask >> i & 1]) if size > best_count or (size == best_count and mask < best_mask): best_count, best_mask = size, mask if best_count == 1 << u: break return [i for i in range(k) if best_mask >> i & 1], best_count if __name__ == '__main__': parser = ArgumentParser(description=__doc__) parser.add_argument('--keep', type=int, required=True) parser.add_argument('weights', type=int, nargs='*') args = parser.parse_args() indices, count = extract(args.weights,args.keep) print(json.dumps({'zero_based_indices':indices,'distinct_sums':count}))