Start by sorting by w_i and consider that if we already have a set of j minimal legitimate solutions (w_i, w_j)(i < j), a set of more optimal solutions (w_u, w_v) must satisfy u < i and j\le v.Notice that both pointers move in one direction, so we just have the excellent practice of moving this double pointer quickly after finding a set of legal solutions to find the optimal solution.
To move the right pointer, we need to look up a section of prefixes that form a legal solution to the right pointer.Notice that the left pointer moves in one direction, so all we need to know is whether there is a legal position in the prefix, which is the smallest legal position at p + 1 after moving the left pointer to a prefix p that does not have a legal position.
Now the question remains, how to quickly find how many of the sets \{S\} intersect a specified set T.Our direct enumeration of the occurrences of a subset of T as a subset of all S won't work because there will be multiple subsets of a set that produce duplicate contributions, and we need a way to remove the redundant contributions.
That is, we need to construct a function F(T) such that \sum_{T\in S}F(T) = 1, and this could not be simpler to construct directly as a tolerance coefficient, i.e., F(T) = (-1)^{\left|T\right|}.
So now the way to find how many of the sets \{S\} intersect a given set T is to enumerate all the subsets of T, count how many times the subset occurs, multiply by the tolerance factor, and sum.Calculating how many times a subset occurs can be done with a hash or a trie, but why not use a trie if you're going to choose a deterministic algorithm of inclusion and exclusion.