Datasets:
Download generator/codegen/fam_structs.py from KreatixLabs/kreatix-code-hard: direct link, hf CLI and curl.
- Browser
- Download file 61 kB
-
https://huggingface.co/datasets/KreatixLabs/kreatix-code-hard/resolve/main/generator/codegen/fam_structs.py
- Command line
-
hf download hf://datasets/KreatixLabs/kreatix-code-hard/generator/codegen/fam_structs.py
-
curl -L -o fam_structs.py https://huggingface.co/datasets/KreatixLabs/kreatix-code-hard/resolve/main/generator/codegen/fam_structs.py
61 kB
"""Graph, DP, search and data-structure families: union-find, Dijkstra, bipartite check, word break, LCS, binary
search on the answer, interval greedy, trie, Fenwick tree and running median. Each sample has an efficient reference
and an independent brute-force oracle. Code is written with FN / CLS as the entry-name placeholder."""
from __future__ import annotations
import random
from .base import Problem, family
def _p(lang, en, fi):
return en if lang == "en" else fi
def _stmt(lang, title, body):
return f"**{_p(lang, *title)}**\n\n{_p(lang, *body)}"
def _edges(rng, n, m, directed=False, wmax=None):
out = []
for _ in range(m):
u, v = rng.randrange(n), rng.randrange(n)
if wmax is None:
out.append([u, v])
else:
out.append([u, v, rng.randint(1, wmax)])
return out
# ----------------------------------------------------------------------------- union-find
@family("union_find", 1.0)
def union_find(rng: random.Random, lang: str) -> Problem:
var = rng.choice(["components", "largest", "first_cycle"])
name = rng.choice({"components": ["count_components", "number_of_groups"], "largest": ["largest_group", "biggest_component"],
"first_cycle": ["first_redundant_edge", "first_cycle_edge"]}[var])
dsu = ''' parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
'''
if var == "components":
body = ''' groups = n
for u, v in edges:
ru, rv = find(u), find(v)
if ru != rv:
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru # union by size keeps the trees shallow
size[ru] += size[rv]
groups -= 1
return groups
'''
oracle = '''def FN(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen, groups = set(), 0
for s in range(n):
if s not in seen:
groups += 1
todo = [s]
seen.add(s)
while todo:
x = todo.pop()
for y in adj[x]:
if y not in seen:
seen.add(y)
todo.append(y)
return groups
'''
ask = ("Return the number of connected groups.", "Palauta yhtenäisten ryhmien määrä.")
ret = "int"
elif var == "largest":
body = ''' for u, v in edges:
ru, rv = find(u), find(v)
if ru != rv:
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru # union by size keeps the trees shallow
size[ru] += size[rv]
return max(size[find(x)] for x in range(n)) if n else 0
'''
oracle = '''def FN(n, edges):
best = 0
for s in range(n):
seen = {s}
changed = True
while changed: # grow the group until no edge adds a new node
changed = False
for u, v in edges:
if (u in seen) != (v in seen):
seen |= {u, v}
changed = True
best = max(best, len(seen))
return best
'''
ask = ("Return the number of nodes in the largest connected group (0 if `n == 0`).",
"Palauta suurimman yhtenäisen ryhmän solmujen määrä (0, jos `n == 0`).")
ret = "int"
else:
body = ''' for u, v in edges:
ru, rv = find(u), find(v)
if ru == rv:
return [u, v] # u and v were already connected: this edge closes a cycle
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru
size[ru] += size[rv]
return []
'''
oracle = '''def FN(n, edges):
added = []
for u, v in edges:
reach, todo = {u}, [u] # is v already reachable from u?
while todo:
x = todo.pop()
for a, b in added:
for p, q in ((a, b), (b, a)):
if p == x and q not in reach:
reach.add(q)
todo.append(q)
if v in reach:
return [u, v]
added.append((u, v))
return []
'''
ask = ("Edges are added one by one in the given order. Return the first edge `[u, v]` whose two ends are "
"already connected when it is added (a self-loop counts), or `[]` if no edge closes a cycle.",
"Kaaret lisätään yksi kerrallaan annetussa järjestyksessä. Palauta ensimmäinen kaari `[u, v]`, jonka "
"päät ovat jo yhteydessä, kun se lisätään (silmukka lasketaan), tai `[]`, jos mikään kaari ei sulje "
"sykliä.")
ret = "list[int]"
sol = "def FN(n, edges):\n" + dsu + body
small = []
for _ in range(14):
n = rng.randint(1, 8)
small.append([n, _edges(rng, n, rng.randint(0, 8))])
edge = [[0, []], [1, []], [1, [[0, 0]]], [3, [[0, 1], [1, 2], [2, 0]]], [4, [[0, 1], [2, 3]]], [5, [[0, 1], [0, 1]]]]
big = lambda: [[200_000, _edges(rng, 200_000, 200_000)]]
stmt = _stmt(lang, ({"components": "Count connected groups", "largest": "Largest connected group",
"first_cycle": "First edge that closes a cycle"}[var],
{"components": "Laske yhtenäiset ryhmät", "largest": "Suurin yhtenäinen ryhmä",
"first_cycle": "Ensimmäinen sykliä sulkeva kaari"}[var]),
(f"There are `n` nodes numbered 0..n-1 and a list of undirected edges `[u, v]`. {ask[0]} `n` and the "
"number of edges can both be 200,000.",
f"Solmuja on `n`, numeroitu 0..n-1, ja suuntaamattomat kaaret annetaan listana `[u, v]`. {ask[1]} "
"Sekä `n` että kaarten määrä voivat olla 200 000."))
approach = _p(lang, "Union-find (disjoint sets) with path halving and union by size: each edge is processed in "
"nearly constant time.",
"Union-find (erilliset joukot) polun puolituksella ja koon mukaan yhdistämällä: jokainen kaari "
"käsitellään lähes vakioajassa.")
plan = _p(lang, ["Keep a parent pointer per node; find() follows it to the group's root.",
"Union by size and path halving keep every find almost O(1).",
{"components": "Every successful union merges two groups, so the count drops by one.",
"largest": "Track the size at each root; the answer is the largest root size.",
"first_cycle": "An edge whose ends already share a root closes a cycle."}[var],
"Edge cases: no nodes, no edges, self-loops, repeated edges."],
["Pidä jokaisella solmulla vanhempiosoitin; find() seuraa sitä ryhmän juureen.",
"Koon mukainen yhdistäminen ja polun puolitus pitävät jokaisen find-kutsun lähes O(1):nä.",
{"components": "Jokainen onnistunut yhdistäminen liittää kaksi ryhmää, joten määrä pienenee yhdellä.",
"largest": "Pidä koko kirjattuna juuressa; vastaus on suurin juuren koko.",
"first_cycle": "Kaari, jonka päillä on jo sama juuri, sulkee syklin."}[var],
"Reunatapaukset: ei solmuja, ei kaaria, silmukat, toistuvat kaaret."])
return Problem("union_find", var, name, f"def {name}(n: int, edges: list[list[int]]) -> {ret}:", stmt,
sol.replace("FN", name), oracle.replace("FN", name), approach, plan,
"O((n + m) α(n)) time, O(n) space", small, edge, big, lang=lang, difficulty=2)
# ----------------------------------------------------------------------------- Dijkstra
@family("dijkstra", 1.0)
def dijkstra(rng, lang):
var = rng.choice(["all", "target"])
name = rng.choice({"all": ["shortest_distances", "all_distances"], "target": ["shortest_path_cost", "fastest_route"]}[var])
if var == "all":
sig = f"def {name}(n: int, edges: list[list[int]], src: int) -> list[int]:"
sol = '''import heapq
def FN(n, edges, src):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
dist = [-1] * n
heap = [(0, src)]
while heap:
d, u = heapq.heappop(heap)
if dist[u] != -1:
continue # already settled with a shorter distance
dist[u] = d
for v, w in adj[u]:
if dist[v] == -1:
heapq.heappush(heap, (d + w, v))
return dist
'''
oracle = '''def FN(n, edges, src):
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(n): # Bellman-Ford: n rounds of relaxing every edge
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return [d if d != INF else -1 for d in dist]
'''
ask = ("Return a list with the length of the shortest path from `src` to every node, or -1 for nodes that "
"cannot be reached.",
"Palauta lista, jossa on lyhimmän polun pituus solmusta `src` jokaiseen solmuun, tai -1 solmuille, "
"joihin ei pääse.")
else:
sig = f"def {name}(n: int, edges: list[list[int]], src: int, dst: int) -> int:"
sol = '''import heapq
def FN(n, edges, src, dst):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
best = [float("inf")] * n
best[src] = 0
heap = [(0, src)]
while heap:
d, u = heapq.heappop(heap)
if u == dst:
return d # the first time dst is popped, its distance is final
if d > best[u]:
continue # stale heap entry
for v, w in adj[u]:
if d + w < best[v]:
best[v] = d + w
heapq.heappush(heap, (d + w, v))
return -1
'''
oracle = '''def FN(n, edges, src, dst):
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(n): # Bellman-Ford: n rounds of relaxing every edge
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist[dst] if dist[dst] != INF else -1
'''
ask = ("Return the length of the shortest path from `src` to `dst`, or -1 if `dst` cannot be reached.",
"Palauta lyhimmän polun pituus solmusta `src` solmuun `dst`, tai -1, jos sinne ei pääse.")
small = []
for _ in range(14):
n = rng.randint(1, 7)
e = _edges(rng, n, rng.randint(0, 12), wmax=9)
small.append([n, e, rng.randrange(n)] + ([rng.randrange(n)] if var == "target" else []))
edge = [[1, [], 0], [2, [], 0], [3, [[0, 1, 5], [1, 2, 5], [0, 2, 20]], 0], [2, [[1, 0, 3]], 0],
[3, [[0, 1, 2], [0, 1, 1], [1, 1, 4]], 0]]
if var == "target":
edge = [e[:3] + [e[0] - 1] for e in edge] + [[1, [], 0, 0]]
nb = 100_000
big = lambda: [[nb, _edges(rng, nb, 300_000, wmax=1000), 0] + ([nb - 1] if var == "target" else [])]
stmt = _stmt(lang, (("Shortest distances from a source" if var == "all" else "Cheapest route to a target"),
("Lyhimmät etäisyydet lähteestä" if var == "all" else "Halvin reitti kohteeseen")),
(f"A directed graph has `n` nodes (0..n-1) and edges `[u, v, w]` from `u` to `v` with weight "
f"`w >= 1`. {ask[0]} There can be 100,000 nodes and 300,000 edges.",
f"Suunnatussa verkossa on `n` solmua (0..n-1) ja kaaret `[u, v, w]` solmusta `u` solmuun `v` "
f"painolla `w >= 1`. {ask[1]} Solmuja voi olla 100 000 ja kaaria 300 000."))
approach = _p(lang, "Dijkstra's algorithm with a binary heap: always settle the closest unsettled node; with "
"positive weights its distance can no longer improve.",
"Dijkstran algoritmi binäärikeolla: vakiinnuta aina lähin vakiinnuttamaton solmu; positiivisilla "
"painoilla sen etäisyys ei voi enää parantua.")
plan = _p(lang, ["All weights are positive, so Dijkstra applies (Bellman-Ford would be O(n·m)).",
"Build an adjacency list once; push (distance, node) pairs on a heap.",
"Skip heap entries that are stale (a shorter distance was already found).",
"Edge cases: src == dst, unreachable nodes, parallel edges, self-loops."],
["Kaikki painot ovat positiivisia, joten Dijkstra toimii (Bellman-Ford olisi O(n·m)).",
"Rakenna vierekkäisyyslista kerran; lisää (etäisyys, solmu) -parit kekoon.",
"Ohita vanhentuneet keon alkiot (lyhyempi etäisyys on jo löytynyt).",
"Reunatapaukset: src == dst, saavuttamattomat solmut, rinnakkaiset kaaret, silmukat."])
return Problem("dijkstra", var, name, sig, stmt, sol.replace("FN", name), oracle.replace("FN", name), approach,
plan, "O((n + m) log m) time, O(n + m) space", small, edge, big, lang=lang, difficulty=2,
time_limit=6.0)
# ----------------------------------------------------------------------------- bipartite check
@family("bipartite", 0.8)
def bipartite(rng, lang):
name = rng.choice(["is_bipartite", "can_split_in_two"])
style = rng.randint(0, 1)
if style == 0:
sol = '''from collections import deque
def FN(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
color = [-1] * n
for s in range(n):
if color[s] != -1:
continue
color[s] = 0
queue = deque([s])
while queue: # BFS: neighbours must get the other colour
u = queue.popleft()
for v in adj[u]:
if color[v] == -1:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
return False
return True
'''
else:
sol = '''def FN(n, edges):
parent = list(range(2 * n)) # node x and its "opposite side" x + n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for u, v in edges:
if find(u) == find(v):
return False # u and v were forced onto the same side
parent[find(u)] = find(v + n) # u goes with the opposite of v
parent[find(v)] = find(u + n)
return True
'''
oracle = '''from itertools import product
def FN(n, edges):
for colors in product((0, 1), repeat=n): # try every 2-colouring: small inputs only
if all(colors[u] != colors[v] for u, v in edges):
return True
return n == 0 and not edges
'''
small = []
for _ in range(14):
n = rng.randint(1, 8)
small.append([n, _edges(rng, n, rng.randint(0, 8))])
edge = [[0, []], [1, []], [1, [[0, 0]]], [3, [[0, 1], [1, 2], [2, 0]]], [4, [[0, 1], [1, 2], [2, 3], [3, 0]]],
[5, [[0, 1], [2, 3]]]]
def big_case():
n = 200_000
side = [rng.randint(0, 1) for _ in range(n)]
left = [i for i in range(n) if side[i] == 0]
right = [i for i in range(n) if side[i] == 1]
return [n, [[rng.choice(left), rng.choice(right)] for _ in range(200_000)]]
big = lambda: [big_case()]
stmt = _stmt(lang, ("Split a graph into two sides", "Jaa verkko kahteen puoleen"),
("There are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split "
"into two groups so that every edge joins nodes from different groups, and False otherwise (a "
"self-loop makes it impossible). There can be 200,000 nodes and edges.",
"Solmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa "
"kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka "
"tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000."))
approach = _p(lang, ("Two-colour every component with BFS; a neighbour that already has the same colour proves "
"it is impossible.") if style == 0 else
("Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with "
"not-u; if u and v ever end up together, it is impossible."),
("Väritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa "
"jaon mahdottomaksi.") if style == 0 else
("Union-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n "
"ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton."))
plan = _p(lang, ["A graph splits in two exactly when it has no odd cycle.",
"Each component is independent: start a new colouring for every uncoloured node.",
"One conflict anywhere is enough to return False.",
"Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle."],
["Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.",
"Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.",
"Yksikin ristiriita riittää palauttamaan False.",
"Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli."])
return Problem("bipartite", f"check{style}", name, f"def {name}(n: int, edges: list[list[int]]) -> bool:", stmt,
sol.replace("FN", name), oracle.replace("FN", name), approach, plan, "O(n + m) time, O(n + m) space"
if style == 0 else "O((n + m) α(n)) time, O(n) space", small, edge, big, lang=lang, difficulty=2)
# ----------------------------------------------------------------------------- word break
WORDS = ["a", "ab", "abc", "b", "ba", "bab", "c", "ca", "cab", "aa", "bc", "cc", "abca", "bca"]
@family("word_break", 1.0)
def word_break(rng, lang):
var = rng.choice(["can", "count", "fewest"])
name = rng.choice({"can": ["can_segment", "word_break"], "count": ["count_segmentations", "segment_ways"],
"fewest": ["fewest_words", "min_word_split"]}[var])
ret = {"can": "bool", "count": "int", "fewest": "int"}[var]
init, combine, final = {
"can": ("[False] * (n + 1)", "best[i] = best[i] or best[i - len(w)]", "best[n]"),
"count": ("[0] * (n + 1)", "best[i] = (best[i] + best[i - len(w)]) % MOD", "best[n]"),
"fewest": ("[INF] * (n + 1)", "best[i] = min(best[i], best[i - len(w)] + 1)", "best[n] if best[n] < INF else -1"),
}[var]
start = {"can": "True", "count": "1", "fewest": "0"}[var]
consts = {"can": "", "count": " MOD = 1_000_000_007\n", "fewest": " INF = float(\"inf\")\n"}[var]
sol = f'''def FN(s, words):
{consts} vocab = set(words)
longest = max(map(len, vocab), default=0)
n = len(s)
best = {init}
best[0] = {start} # the empty prefix
for i in range(1, n + 1):
for k in range(1, min(longest, i) + 1): # only word lengths that exist need checking
w = s[i - k:i]
if w in vocab:
{combine}
return {final}
'''
oracle_body = {
"can": ("any(go(i + len(w)) for w in set(words) if s.startswith(w, i) and w)", "True"),
"count": ("sum(go(i + len(w)) for w in set(words) if s.startswith(w, i) and w)", "1"),
"fewest": ("min((1 + go(i + len(w)) for w in set(words) if s.startswith(w, i) and w), default=float('inf'))", "0"),
}[var]
post = {"can": "go(0)", "count": "go(0) % 1_000_000_007", "fewest": "go(0) if go(0) != float('inf') else -1"}[var]
oracle = f'''def FN(s, words):
def go(i): # try every first word, no memo: small inputs only
if i == len(s):
return {oracle_body[1]}
return {oracle_body[0]}
return {post}
'''
def case(n):
ws = rng.sample(WORDS, rng.randint(1, 6))
if rng.random() < 0.7:
parts, total = [], 0
while total < n:
w = rng.choice(ws)
parts.append(w)
total += len(w)
s = "".join(parts)
else:
s = "".join(rng.choice("abc") for _ in range(n))
return [s, ws]
small = [case(rng.randint(0, 11)) for _ in range(14)]
edge = [["", ["a"]], ["", []], ["a", []], ["aaaa", ["a", "aa"]], ["abc", ["ab", "bc"]], ["cab", ["c", "ab", "cab"]]]
def big_case():
ws = ["".join(rng.choice("ab") for _ in range(rng.randint(1, 8))) for _ in range(200)]
return ["".join(rng.choice(ws) for _ in range(5_000)), ws]
big = lambda: [big_case()]
ask = {"can": ("Return True if `s` can be split into a sequence of one or more words from `words` (each word can "
"be used any number of times), and False otherwise. The empty string counts as splittable.",
"Palauta True, jos `s` voidaan jakaa yhden tai useamman listan `words` sanan jonoksi (jokaista sanaa "
"saa käyttää kuinka monesti tahansa), ja muuten False. Tyhjä jono lasketaan jaettavaksi."),
"count": ("Return the number of different ways to split `s` into words from `words` (each word can be used "
"any number of times), modulo 1,000,000,007. The empty string has exactly one split.",
"Palauta, kuinka monella eri tavalla `s` voidaan jakaa listan `words` sanoiksi (jokaista sanaa saa "
"käyttää kuinka monesti tahansa), modulo 1 000 000 007. Tyhjällä jonolla on täsmälleen yksi jako."),
"fewest": ("Return the smallest number of words from `words` that concatenate to exactly `s` (each word can "
"be used any number of times), or -1 if it is impossible. The empty string needs 0 words.",
"Palauta pienin määrä listan `words` sanoja, jotka peräkkäin muodostavat täsmälleen jonon `s` "
"(jokaista sanaa saa käyttää kuinka monesti tahansa), tai -1, jos se on mahdotonta. Tyhjä jono "
"tarvitsee 0 sanaa.")}[var]
stmt = _stmt(lang, ({"can": "Word break", "count": "Count word splits", "fewest": "Fewest words"}[var],
{"can": "Sanoiksi jakaminen", "count": "Laske sanajaot", "fewest": "Vähiten sanoja"}[var]),
(ask[0] + " `s` can be tens of thousands of characters long.",
ask[1] + " `s` voi olla kymmeniä tuhansia merkkejä pitkä."))
approach = _p(lang, "Dynamic programming over prefixes: best[i] describes s[:i], and it is built from best[i - k] "
"for every word length k whose last k characters form a word.",
"Dynaaminen ohjelmointi etuliitteiden yli: best[i] kuvaa jonoa s[:i], ja se rakennetaan arvoista "
"best[i - k] jokaiselle sanan pituudelle k, jonka viimeiset k merkkiä muodostavat sanan.")
plan = _p(lang, ["Trying every split recursively is exponential; each prefix only needs to be solved once.",
"Put the words in a set and only try lengths up to the longest word.",
{"can": "best[i] is True if some word ends at i after a splittable prefix.",
"count": "Add up the counts of every prefix that a word extends to i.",
"fewest": "Take the minimum over words ending at i, plus one."}[var],
"Edge cases: empty string, empty word list, overlapping words."],
["Kaikkien jakojen kokeileminen rekursiivisesti on eksponentiaalista; jokainen etuliite ratkaistaan kerran.",
"Laita sanat joukkoon ja kokeile vain pituuksia pisimpään sanaan asti.",
{"can": "best[i] on True, jos jokin sana päättyy kohtaan i jaettavan etuliitteen jälkeen.",
"count": "Laske yhteen jokaisen etuliitteen määrät, joita jokin sana jatkaa kohtaan i.",
"fewest": "Ota minimi kohtaan i päättyvien sanojen yli, plus yksi."}[var],
"Reunatapaukset: tyhjä jono, tyhjä sanalista, päällekkäiset sanat."])
return Problem("word_break", var, name, f"def {name}(s: str, words: list[str]) -> {ret}:", stmt,
sol.replace("FN", name), oracle.replace("FN", name), approach, plan,
"O(n · L) set lookups (L = longest word length), O(n) space", small, edge, big, lang=lang,
difficulty=2)
# ----------------------------------------------------------------------------- longest common subsequence / substring
@family("common_sequence", 1.0)
def common_sequence(rng, lang):
var = rng.choice(["subseq", "substring"])
name = rng.choice({"subseq": ["lcs_length", "longest_common_subsequence"],
"substring": ["longest_common_substring", "common_substring_len"]}[var])
if var == "subseq":
sol = '''def FN(a, b):
prev = [0] * (len(b) + 1) # row for the previous prefix of a
for ca in a:
cur = [0] * (len(b) + 1)
for j, cb in enumerate(b, 1):
cur[j] = prev[j - 1] + 1 if ca == cb else max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
'''
oracle = '''from itertools import combinations
def FN(a, b):
for k in range(min(len(a), len(b)), 0, -1): # try subsequences of a from longest down: small inputs only
for idx in combinations(range(len(a)), k):
sub = [a[i] for i in idx]
it = iter(b)
if all(ch in it for ch in sub): # is sub a subsequence of b?
return k
return 0
'''
what = ("the length of the longest common subsequence of `a` and `b` (characters in the same order, not "
"necessarily adjacent)",
"merkkijonojen `a` ja `b` pisimmän yhteisen alijonon pituus (merkit samassa järjestyksessä, ei "
"välttämättä vierekkäin)")
else:
sol = '''def FN(a, b):
best = 0
prev = [0] * (len(b) + 1) # prev[j]: common run ending at the previous char of a and b[j - 1]
for ca in a:
cur = [0] * (len(b) + 1)
for j, cb in enumerate(b, 1):
if ca == cb:
cur[j] = prev[j - 1] + 1
if cur[j] > best:
best = cur[j]
prev = cur
return best
'''
oracle = '''def FN(a, b):
best = 0
for i in range(len(a)):
for j in range(i + 1, len(a) + 1):
if a[i:j] in b:
best = max(best, j - i)
return best
'''
what = ("the length of the longest string that appears as a contiguous substring in both `a` and `b`",
"pisimmän sellaisen merkkijonon pituus, joka esiintyy yhtenäisenä osajonona sekä jonossa `a` että `b`")
small = [["".join(rng.choice("abc") for _ in range(rng.randint(0, 8))),
"".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))] for _ in range(14)]
edge = [["", ""], ["abc", ""], ["abc", "abc"], ["abc", "def"], ["abcde", "ace"], ["xabcy", "zabcw"]]
big = lambda: [["".join(rng.choice("acgt") for _ in range(1_300)), "".join(rng.choice("acgt") for _ in range(1_300))]]
stmt = _stmt(lang, (("Longest common subsequence" if var == "subseq" else "Longest common substring"),
("Pisin yhteinen alijono" if var == "subseq" else "Pisin yhteinen osajono")),
(f"Return {what[0]}. Both strings can be over a thousand characters long.",
f"Palauta {what[1]}. Molemmat jonot voivat olla yli tuhat merkkiä pitkiä."))
approach = _p(lang, "Dynamic programming over prefixes of both strings, keeping only the previous row: " +
("matching characters extend the diagonal, otherwise take the better of dropping one character."
if var == "subseq" else
"a match extends the common run ending at the previous characters, a mismatch resets it to 0."),
"Dynaaminen ohjelmointi molempien jonojen etuliitteiden yli, vain edellinen rivi muistissa: " +
("täsmäävät merkit jatkavat diagonaalia, muuten valitaan parempi kahdesta yhden merkin pudotuksesta."
if var == "subseq" else
"täsmäys jatkaa edellisiin merkkeihin päättyvää yhteistä jaksoa, ero nollaa sen."))
plan = _p(lang, ["Enumerating " + ("subsequences is exponential" if var == "subseq" else "every pair of substrings is O(n³) or worse") +
"; a table over prefix pairs is O(n·m).",
("dp[i][j] = dp[i-1][j-1] + 1 on a match, else max(dp[i-1][j], dp[i][j-1])." if var == "subseq" else
"dp[i][j] = dp[i-1][j-1] + 1 on a match, else 0; the answer is the largest entry."),
"Each row only depends on the previous one, so O(m) memory is enough.",
"Edge cases: an empty string, identical strings, no common character."],
["Kaikkien " + ("alijonojen läpikäynti on eksponentiaalista" if var == "subseq" else "osajonoparien läpikäynti on O(n³) tai pahempi") +
"; taulukko etuliiteparien yli on O(n·m).",
("dp[i][j] = dp[i-1][j-1] + 1 täsmätessä, muuten max(dp[i-1][j], dp[i][j-1])." if var == "subseq" else
"dp[i][j] = dp[i-1][j-1] + 1 täsmätessä, muuten 0; vastaus on suurin arvo."),
"Jokainen rivi riippuu vain edellisestä, joten O(m)-muisti riittää.",
"Reunatapaukset: tyhjä jono, identtiset jonot, ei yhteisiä merkkejä."])
return Problem("common_sequence", var, name, f"def {name}(a: str, b: str) -> int:", stmt, sol.replace("FN", name),
oracle.replace("FN", name), approach, plan, "O(len(a) · len(b)) time, O(len(b)) space", small, edge,
big, lang=lang, difficulty=2, time_limit=6.0)
# ----------------------------------------------------------------------------- binary search on the answer
@family("search_answer", 1.0)
def search_answer(rng, lang):
var = rng.choice(["ship", "speed"])
if var == "ship":
name = rng.choice(["min_ship_capacity", "smallest_capacity"])
sig = f"def {name}(weights: list[int], days: int) -> int:"
check = ''' def fits(cap): # greedy: fill each day as much as possible
used, load = 1, 0
for w in weights:
if load + w > cap:
used, load = used + 1, 0
load += w
return used <= days
lo, hi = max(weights), sum(weights)
'''
oracle = '''def FN(weights, days):
cap = max(weights)
while True: # try every capacity upward: small inputs only
used, load = 1, 0
for w in weights:
if load + w > cap:
used, load = used + 1, 0
load += w
if used <= days:
return cap
cap += 1
'''
args = "weights, days"
small = []
for _ in range(14):
ws = [rng.randint(1, 9) for _ in range(rng.randint(1, 9))]
small.append([ws, rng.randint(1, len(ws))])
edge = [[[5], 1], [[1, 1, 1], 3], [[1, 2, 3, 4, 5], 1], [[3, 2, 2, 4, 1, 4], 3], [[10, 1, 1], 2]]
big = lambda: [[[rng.randint(1, 10**4) for _ in range(300_000)], 1_000]]
stmt = _stmt(lang, ("Smallest ship capacity", "Pienin laivan kapasiteetti"),
("Packages with weights `weights` must be shipped in the given order within `days` days "
"(1 <= days <= len(weights)). Each day the ship takes a run of consecutive packages whose total "
"weight does not exceed its capacity. Return the smallest capacity that makes this possible. "
"There can be 300,000 packages.",
"Paketit painoilla `weights` on kuljetettava annetussa järjestyksessä `days` päivässä "
"(1 <= days <= len(weights)). Joka päivä laiva ottaa peräkkäisiä paketteja, joiden yhteispaino ei "
"ylitä sen kapasiteettia. Palauta pienin kapasiteetti, jolla tämä onnistuu. Paketteja voi olla "
"300 000."))
mono = _p(lang, "a larger capacity never needs more days", "suurempi kapasiteetti ei koskaan tarvitse enempää päiviä")
bounds = _p(lang, "between max(weights) (the heaviest package must fit) and sum(weights) (one day)",
"välillä max(weights) (painavimman paketin on mahduttava) ja sum(weights) (yksi päivä)")
else:
name = rng.choice(["min_eating_speed", "slowest_speed"])
sig = f"def {name}(piles: list[int], hours: int) -> int:"
check = ''' def fits(speed): # hours needed at this speed, rounding each pile up
return sum((p + speed - 1) // speed for p in piles) <= hours
lo, hi = 1, max(piles)
'''
oracle = '''def FN(piles, hours):
speed = 1
while sum(-(-p // speed) for p in piles) > hours: # try every speed upward: small inputs only
speed += 1
return speed
'''
args = "piles, hours"
small = []
for _ in range(14):
ps = [rng.randint(1, 20) for _ in range(rng.randint(1, 7))]
small.append([ps, rng.randint(len(ps), len(ps) + 8)])
edge = [[[1], 1], [[30], 1], [[30], 30], [[3, 6, 7, 11], 8], [[30, 11, 23, 4, 20], 5]]
big = lambda: [[[rng.randint(1, 10**9) for _ in range(300_000)], 600_000]]
stmt = _stmt(lang, ("Slowest speed that finishes in time", "Hitain riittävä nopeus"),
("There are piles of items `piles`. At speed `k` you take up to `k` items from one pile per hour "
"(a pile with fewer items still takes the whole hour). Return the smallest integer speed that "
"finishes every pile within `hours` hours (len(piles) <= hours). There can be 300,000 piles with "
"up to 10^9 items each.",
"Kasoja on `piles`. Nopeudella `k` otat yhdestä kasasta enintään `k` esinettä tunnissa (kasa, "
"jossa on vähemmän, vie silti koko tunnin). Palauta pienin kokonaislukunopeus, jolla kaikki kasat "
"ehtii `hours` tunnissa (len(piles) <= hours). Kasoja voi olla 300 000, ja kussakin enintään 10^9 "
"esinettä."))
mono = _p(lang, "a higher speed never needs more hours", "suurempi nopeus ei koskaan tarvitse enempää tunteja")
bounds = _p(lang, "between 1 and max(piles) (one hour per pile)", "välillä 1 ja max(piles) (tunti kasaa kohden)")
sol = f"def FN({args}):\n" + check + ''' while lo < hi: # smallest value for which fits() is True
mid = (lo + hi) // 2
if fits(mid):
hi = mid
else:
lo = mid + 1
return lo
'''
approach = _p(lang, f"Binary search on the answer: {mono}, so test a candidate with a linear greedy check and "
f"halve the range {bounds}.",
f"Binäärihaku vastauksen yli: {mono}, joten testaa ehdokas lineaarisella ahneella tarkistuksella ja "
f"puolita väli {bounds}.")
plan = _p(lang, ["Checking one candidate is easy and linear; finding the best candidate directly is not.",
f"The check is monotonic ({mono}), which is what makes binary search valid.",
"Search for the first value where the check passes (lo < hi, hi = mid on success).",
"Edge cases: one item, the tightest limit, the loosest limit."],
["Yhden ehdokkaan tarkistus on helppo ja lineaarinen; parhaan löytäminen suoraan ei ole.",
f"Tarkistus on monotoninen ({mono}), mikä tekee binäärihausta pätevän.",
"Etsi ensimmäinen arvo, jolla tarkistus menee läpi (lo < hi, onnistuessa hi = mid).",
"Reunatapaukset: yksi alkio, tiukin raja, väljin raja."])
return Problem("search_answer", var, name, sig, stmt, sol.replace("FN", name), oracle.replace("FN", name),
approach, plan, "O(n log R) time (R = size of the answer range), O(1) space", small, edge, big,
lang=lang, difficulty=2)
# ----------------------------------------------------------------------------- interval greedy
@family("interval_greedy", 1.0)
def interval_greedy(rng, lang):
var = rng.choice(["keep", "remove", "points"])
name = rng.choice({"keep": ["max_non_overlapping", "most_meetings"], "remove": ["min_removals", "fewest_to_cancel"],
"points": ["min_points_to_cover", "fewest_stabs"]}[var])
touch_ok = var != "points"
cmp = ">=" if touch_ok else ">"
sol = f'''def FN(intervals):
count, end = 0, float("-inf")
for s, e in sorted(intervals, key=lambda iv: iv[1]): # earliest end first
if s {cmp} end:
count += 1 # {"keep this interval" if var != "points" else "this interval needs a new point at e"}
end = e
return {"count" if var != "remove" else "len(intervals) - count"}
'''
if var == "points":
oracle = '''from itertools import combinations
def FN(intervals):
if not intervals:
return 0
ends = sorted({e for _, e in intervals}) # some optimal set of points uses only interval ends
for k in range(1, len(ends) + 1):
for pts in combinations(ends, k):
if all(any(s <= p <= e for p in pts) for s, e in intervals):
return k
'''
else:
ret = "best" if var == "keep" else "len(intervals) - best"
oracle = f'''from itertools import combinations
def FN(intervals):
best = 0
for k in range(len(intervals), 0, -1): # largest subset whose intervals do not overlap: small inputs only
if any(all(max(a[0], b[0]) >= min(a[1], b[1]) for a, b in combinations(sub, 2))
for sub in combinations(intervals, k)):
best = k
break
return {ret}
'''
def ivs(n, hi):
out = []
for _ in range(n):
a = rng.randint(0, hi - 1)
out.append([a, rng.randint(a + 1, min(hi, a + max(2, hi // 3)))])
return out
small = [[ivs(rng.randint(0, 8), 20)] for _ in range(14)]
edge = [[[]], [[[1, 2]]], [[[1, 2], [2, 3]]], [[[1, 5], [2, 3], [3, 4]]], [[[1, 3], [1, 3], [1, 3]]], [[[1, 10], [2, 3], [4, 5], [6, 7]]]]
big = lambda: [[ivs(300_000, 10**9)]]
ask = {"keep": ("Return the largest number of intervals you can keep so that no two of them overlap. Intervals "
"that only touch (`[1, 2]` and `[2, 3]`) do not overlap.",
"Palauta suurin määrä välejä, jotka voi pitää niin, ettei mitkään kaksi mene päällekkäin. Välit, "
"jotka vain koskettavat (`[1, 2]` ja `[2, 3]`), eivät mene päällekkäin."),
"remove": ("Return the smallest number of intervals to remove so that the rest do not overlap. Intervals "
"that only touch (`[1, 2]` and `[2, 3]`) do not overlap.",
"Palauta pienin määrä välejä, jotka on poistettava, jotta loput eivät mene päällekkäin. Välit, "
"jotka vain koskettavat (`[1, 2]` ja `[2, 3]`), eivät mene päällekkäin."),
"points": ("Return the smallest number of points such that every interval contains at least one of them "
"(endpoints included, so the point 2 covers both `[1, 2]` and `[2, 3]`).",
"Palauta pienin määrä pisteitä niin, että jokainen väli sisältää ainakin yhden niistä (päätepisteet "
"mukaan lukien, joten piste 2 kattaa sekä välin `[1, 2]` että `[2, 3]`).")}[var]
stmt = _stmt(lang, ({"keep": "Keep the most non-overlapping intervals", "remove": "Fewest intervals to remove",
"points": "Fewest points that cover every interval"}[var],
{"keep": "Eniten päällekkäisyyksiä välttäviä välejä", "remove": "Vähiten poistettavia välejä",
"points": "Vähiten pisteitä, jotka kattavat jokaisen välin"}[var]),
(f"You are given intervals `[start, end]` with `start < end`. {ask[0]} There can be 300,000 intervals.",
f"Saat välit `[start, end]`, joissa `start < end`. {ask[1]} Välejä voi olla 300 000."))
approach = _p(lang, "Greedy by earliest end: sort by end, and " +
("keep an interval whenever it starts at or after the end of the last kept one."
if var != "points" else
"place a point at an interval's end whenever the last point does not already cover it."),
"Ahne valinta aikaisimman lopun mukaan: järjestä lopun mukaan ja " +
("pidä väli aina, kun se alkaa viimeksi pidetyn lopussa tai sen jälkeen."
if var != "points" else
"aseta piste välin loppuun aina, kun viimeinen piste ei jo kata sitä."))
plan = _p(lang, ["Exchange argument: the interval that ends first leaves the most room for the rest.",
("So the greedy count is the most intervals you can keep" +
("; the answer is how many are left over." if var == "remove" else ".")) if var != "points" else
"A point at the earliest end covers every interval that starts before it.",
("Touching is allowed, so compare start >= last end." if var != "points" else
"Endpoints count, so a new point is needed only when start > last point."),
"Edge cases: empty list, identical intervals, one long interval containing short ones."],
["Vaihtoargumentti: ensimmäisenä päättyvä väli jättää eniten tilaa muille.",
("Ahne määrä on siis suurin pidettävien välien määrä" +
("; vastaus on yli jäävien määrä." if var == "remove" else ".")) if var != "points" else
"Piste aikaisimmassa lopussa kattaa jokaisen välin, joka alkaa ennen sitä.",
("Koskettaminen sallitaan, joten vertaa start >= viimeinen loppu." if var != "points" else
"Päätepisteet lasketaan, joten uusi piste tarvitaan vain, kun start > viimeinen piste."),
"Reunatapaukset: tyhjä lista, identtiset välit, yksi pitkä väli lyhyiden ympärillä."])
return Problem("interval_greedy", var, name, f"def {name}(intervals: list[list[int]]) -> int:", stmt,
sol.replace("FN", name), oracle.replace("FN", name), approach, plan,
"O(n log n) time for the sort, O(n) space", small, edge, big, lang=lang, difficulty=2)
# ----------------------------------------------------------------------------- trie / prefix counter (class)
@family("prefix_counter", 0.9)
def prefix_counter(rng, lang):
cls = rng.choice(["PrefixCounter", "WordIndex"])
style = rng.randint(0, 1)
if style == 0:
sol = '''class CLS:
def __init__(self):
self.root = {} # nested dicts; "#" holds counts at each node
def insert(self, word):
node = self.root
node["#"] = node.get("#", 0) + 1
for ch in word:
node = node.setdefault(ch, {})
node["#"] = node.get("#", 0) + 1 # words passing through this prefix
node["$"] = node.get("$", 0) + 1 # words ending exactly here
def _walk(self, text):
node = self.root
for ch in text:
node = node.get(ch)
if node is None:
return None
return node
def count(self, word):
node = self._walk(word)
return node.get("$", 0) if node else 0
def starts_with(self, prefix):
node = self._walk(prefix)
return node.get("#", 0) if node else 0
'''
else:
sol = '''from collections import Counter
class CLS:
def __init__(self):
self.prefixes = Counter() # every prefix of every inserted word
self.words = Counter()
def insert(self, word):
self.words[word] += 1
for i in range(len(word) + 1):
self.prefixes[word[:i]] += 1
def count(self, word):
return self.words[word]
def starts_with(self, prefix):
return self.prefixes[prefix]
'''
oracle = '''class CLS:
def __init__(self):
self.items = []
def insert(self, word):
self.items.append(word)
def count(self, word):
return sum(1 for w in self.items if w == word)
def starts_with(self, prefix):
return sum(1 for w in self.items if w.startswith(prefix))
'''
def word():
return "".join(rng.choice("abc") for _ in range(rng.randint(0, 4)))
def seq(n):
ops = []
for _ in range(n):
r = rng.random()
ops.append(["insert", word()] if r < 0.5 else ["count", word()] if r < 0.7 else ["starts_with", word()])
return {"init": [], "ops": ops}
small = [seq(rng.randint(3, 20)) for _ in range(14)]
edge = [{"init": [], "ops": [["starts_with", ""], ["count", ""], ["insert", ""], ["count", ""], ["starts_with", ""]]},
{"init": [], "ops": [["insert", "ab"], ["insert", "ab"], ["count", "ab"], ["count", "a"], ["starts_with", "a"]]},
{"init": [], "ops": [["insert", "abc"], ["starts_with", "abcd"], ["count", "abcd"], ["starts_with", "abc"]]}]
def big_seq():
vocab = ["".join(rng.choice("abcdefgh") for _ in range(rng.randint(1, 10))) for _ in range(20_000)]
ops = []
for _ in range(100_000):
w = rng.choice(vocab)
r = rng.random()
ops.append(["insert", w] if r < 0.5 else ["count", w] if r < 0.75 else ["starts_with", w[:rng.randint(0, len(w))]])
return {"init": [], "ops": ops}
big = lambda: [big_seq()]
stmt = _stmt(lang, ("Prefix counter", "Etuliitelaskuri"),
(f"Implement `{cls}()` with three methods: `insert(word)` adds a word (duplicates count again), "
"`count(word)` returns how many times exactly `word` was inserted, and `starts_with(prefix)` returns "
"how many inserted words start with `prefix` (every word starts with the empty prefix). There can be "
"100,000 operations, so scanning all words per query is too slow.",
f"Toteuta `{cls}()`, jossa on kolme metodia: `insert(word)` lisää sanan (toistot lasketaan uudelleen), "
"`count(word)` palauttaa, montako kertaa täsmälleen `word` on lisätty, ja `starts_with(prefix)` "
"palauttaa, moniko lisätty sana alkaa etuliitteellä `prefix` (jokainen sana alkaa tyhjällä "
"etuliitteellä). Operaatioita voi olla 100 000, joten kaikkien sanojen läpikäynti kyselyä kohden on "
"liian hidasta."))
approach = _p(lang, ("A trie of nested dicts that stores, at every node, how many words pass through it and how "
"many end there; each operation walks one path.") if style == 0 else
("Count every prefix of each inserted word in a hash map; each query is then a single lookup."),
("Sisäkkäisistä sanakirjoista tehty trie, joka tallentaa jokaiseen solmuun, moniko sana kulkee sen "
"kautta ja moniko päättyy siihen; jokainen operaatio kulkee yhden polun.") if style == 0 else
("Laske jokaisen lisätyn sanan jokainen etuliite hajautustauluun; jokainen kysely on silloin yksi "
"haku."))
plan = _p(lang, ["Move the work to insert time: queries must not look at every word.",
"Keep two counts per prefix: words passing through and words ending exactly there.",
"Every word passes through the empty prefix, so starts_with('') is the number of words.",
"Edge cases: the empty word, duplicates, a query longer than any word."],
["Siirrä työ lisäyshetkeen: kyselyt eivät saa käydä jokaista sanaa läpi.",
"Pidä kaksi laskuria etuliitettä kohden: sen kautta kulkevat ja täsmälleen siihen päättyvät sanat.",
"Jokainen sana kulkee tyhjän etuliitteen kautta, joten starts_with('') on sanojen määrä.",
"Reunatapaukset: tyhjä sana, toistot, kaikkia sanoja pidempi kysely."])
sig = (f"class {cls}:\n def __init__(self): ...\n def insert(self, word: str) -> None: ...\n"
" def count(self, word: str) -> int: ...\n def starts_with(self, prefix: str) -> int: ...")
return Problem("prefix_counter", f"class{style}", cls, sig, stmt, sol.replace("CLS", cls), oracle.replace("CLS", cls),
approach, plan, "O(len(word)) per operation" + (", O(total length) space" if style == 0 else
", O(total length²) space for the prefixes"),
small, edge, big, kind="class", lang=lang, difficulty=2)
# ----------------------------------------------------------------------------- range sums with updates (class)
@family("range_sum", 0.9)
def range_sum(rng, lang):
cls = rng.choice(["RangeSum", "PointUpdateSums"])
style = rng.randint(0, 1)
if style == 0:
sol = '''class CLS:
def __init__(self, nums):
self.n = len(nums)
self.vals = list(nums)
self.tree = [0] * (self.n + 1) # Fenwick tree, 1-based
for i, x in enumerate(nums):
self._add(i + 1, x)
def _add(self, i, delta):
while i <= self.n:
self.tree[i] += delta
i += i & -i
def _prefix(self, i): # sum of the first i values
total = 0
while i > 0:
total += self.tree[i]
i -= i & -i
return total
def update(self, index, value):
self._add(index + 1, value - self.vals[index])
self.vals[index] = value
def query(self, left, right):
return self._prefix(right + 1) - self._prefix(left)
'''
else:
sol = '''class CLS:
def __init__(self, nums):
self.size = 1
while self.size < len(nums):
self.size *= 2
self.tree = [0] * (2 * self.size) # iterative segment tree: leaves at size .. 2 * size - 1
for i, x in enumerate(nums):
self.tree[self.size + i] = x
for i in range(self.size - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def update(self, index, value):
i = self.size + index
self.tree[i] = value
i //= 2
while i:
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
i //= 2
def query(self, left, right):
total = 0
lo, hi = left + self.size, right + self.size + 1 # half-open [lo, hi)
while lo < hi:
if lo & 1:
total += self.tree[lo]
lo += 1
if hi & 1:
hi -= 1
total += self.tree[hi]
lo //= 2
hi //= 2
return total
'''
oracle = '''class CLS:
def __init__(self, nums):
self.vals = list(nums)
def update(self, index, value):
self.vals[index] = value
def query(self, left, right):
return sum(self.vals[left:right + 1])
'''
def seq(n, m, lo=-9, hi=9):
nums = [rng.randint(lo, hi) for _ in range(n)]
ops = []
for _ in range(m):
if rng.random() < 0.45:
ops.append(["update", rng.randrange(n), rng.randint(lo, hi)])
else:
a, b = sorted(rng.randrange(n) for _ in range(2))
ops.append(["query", a, b])
return {"init": [nums], "ops": ops}
small = [seq(rng.randint(1, 9), rng.randint(2, 14)) for _ in range(14)]
edge = [{"init": [[5]], "ops": [["query", 0, 0], ["update", 0, -3], ["query", 0, 0]]},
{"init": [[1, 2, 3]], "ops": [["update", 1, 2], ["query", 0, 2], ["query", 1, 1]]},
{"init": [[0, 0, 0, 0]], "ops": [["update", 3, 7], ["query", 0, 3], ["query", 0, 2]]}]
big = lambda: [seq(100_000, 150_000, -10**6, 10**6)]
stmt = _stmt(lang, ("Range sums with updates", "Välisummat päivityksillä"),
(f"Implement `{cls}(nums)` with `update(index, value)`, which sets `nums[index] = value`, and "
"`query(left, right)`, which returns the sum of `nums[left..right]` (both ends included, "
"`left <= right`). There can be 100,000 values and 150,000 operations, so summing the range for "
"every query is too slow.",
f"Toteuta `{cls}(nums)`, jossa `update(index, value)` asettaa `nums[index] = value` ja "
"`query(left, right)` palauttaa summan `nums[left..right]` (molemmat päät mukaan lukien, "
"`left <= right`). Arvoja voi olla 100 000 ja operaatioita 150 000, joten välin summaaminen joka "
"kyselyllä on liian hidasta."))
approach = _p(lang, ("A Fenwick (binary indexed) tree: an update adds the difference along O(log n) nodes, and a "
"range sum is the difference of two prefix sums.") if style == 0 else
("An iterative segment tree: an update rewrites one leaf and its O(log n) ancestors, and a "
"query combines O(log n) nodes that exactly cover the range."),
("Fenwick-puu: päivitys lisää erotuksen O(log n) solmuun, ja välisumma on kahden etuliitesumman "
"erotus.") if style == 0 else
("Iteratiivinen segmenttipuu: päivitys kirjoittaa yhden lehden ja sen O(log n) esivanhempaa, ja "
"kysely yhdistää O(log n) solmua, jotka kattavat välin täsmälleen."))
plan = _p(lang, ["A plain list makes queries O(n); prefix sums make updates O(n). A tree balances both.",
("Store the current values too: update(index, value) adds value - old." if style == 0 else
"Pad the size to a power of two so children of node i are 2i and 2i + 1."),
"Both operations are O(log n).",
"Edge cases: one value, a range of length 1, updating to the same value, negative numbers."],
["Pelkkä lista tekee kyselyistä O(n); etuliitesummat tekevät päivityksistä O(n). Puu tasapainottaa molemmat.",
("Säilytä myös nykyiset arvot: update(index, value) lisää value - vanha." if style == 0 else
"Täydennä koko kahden potenssiksi, jolloin solmun i lapset ovat 2i ja 2i + 1."),
"Molemmat operaatiot ovat O(log n).",
"Reunatapaukset: yksi arvo, pituuden 1 väli, päivitys samaan arvoon, negatiiviset luvut."])
sig = (f"class {cls}:\n def __init__(self, nums: list[int]): ...\n"
" def update(self, index: int, value: int) -> None: ...\n def query(self, left: int, right: int) -> int: ...")
return Problem("range_sum", f"class{style}", cls, sig, stmt, sol.replace("CLS", cls), oracle.replace("CLS", cls),
approach, plan, "O(n) to build, O(log n) per operation, O(n) space", small, edge, big, kind="class",
lang=lang, difficulty=3, time_limit=6.0)
# ----------------------------------------------------------------------------- running median (class)
@family("running_median", 0.9)
def running_median(rng, lang):
cls = rng.choice(["MedianTracker", "StreamMedian"])
var = rng.choice(["avg", "low"])
med = ("(-self.low[0] + self.high[0]) / 2" if var == "avg" else "-self.low[0]")
sol = f'''import heapq
class CLS:
def __init__(self):
self.low = [] # max-heap (negated) with the smaller half
self.high = [] # min-heap with the larger half
def add(self, x):
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element
def median(self):
if len(self.low) > len(self.high):
return -self.low[0]
return {med}
'''
omed = "(s[k - 1] + s[k]) / 2" if var == "avg" else "s[k - 1]"
oracle = f'''class CLS:
def __init__(self):
self.items = []
def add(self, x):
self.items.append(x)
def median(self):
s = sorted(self.items)
k = len(s) // 2
return s[k] if len(s) % 2 else {omed}
'''
def seq(n, lo=-20, hi=20):
ops = [["add", rng.randint(lo, hi)]]
for _ in range(n):
ops.append(["add", rng.randint(lo, hi)] if rng.random() < 0.6 else ["median"])
ops.append(["median"])
return {"init": [], "ops": ops}
small = [seq(rng.randint(2, 16)) for _ in range(14)]
edge = [{"init": [], "ops": [["add", 5], ["median"]]},
{"init": [], "ops": [["add", 1], ["add", 2], ["median"], ["add", 3], ["median"]]},
{"init": [], "ops": [["add", 4], ["add", 4], ["add", 4], ["median"], ["add", -4], ["median"]]}]
big = lambda: [seq(200_000, -10**9, 10**9)]
even = (("the mean of the two middle values (a float, e.g. 2.5)", "kahden keskimmäisen arvon keskiarvo (liukuluku, "
"esim. 2.5)") if var == "avg" else
("the lower of the two middle values", "kahdesta keskimmäisestä arvosta pienempi"))
stmt = _stmt(lang, ("Running median", "Juokseva mediaani"),
(f"Implement `{cls}()` with `add(x)`, which adds an integer, and `median()`, which returns the median "
f"of all numbers added so far (at least one). For an even count the median is {even[0]}. There can "
"be 200,000 operations, so sorting on every call is too slow.",
f"Toteuta `{cls}()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti "
f"lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on {even[1]}. "
"Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta."))
approach = _p(lang, "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced "
"so the median is always at the top of one or both.",
"Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että "
"mediaani on aina toisen tai molempien huipulla.")
plan = _p(lang, ["Only the middle matters, so keep the two halves apart instead of a sorted list.",
"Push into the low half, move its largest to the high half, and rebalance so low has the extra item.",
"Python's heapq is a min-heap: store negated values for the max-heap.",
"Edge cases: one number, duplicates, negative numbers, even and odd counts."],
["Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.",
"Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.",
"Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.",
"Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä."])
rt = "float" if var == "avg" else "int"
sig = f"class {cls}:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> {rt}: ..."
return Problem("running_median", var, cls, sig, stmt, sol.replace("CLS", cls), oracle.replace("CLS", cls),
approach, plan, "O(log n) per add, O(1) per median, O(n) space", small, edge, big, kind="class",
lang=lang, difficulty=3)
"""Graph, DP, search and data-structure families: union-find, Dijkstra, bipartite check, word break, LCS, binary
search on the answer, interval greedy, trie, Fenwick tree and running median. Each sample has an efficient reference
and an independent brute-force oracle. Code is written with FN / CLS as the entry-name placeholder."""
from __future__ import annotations
import random
from .base import Problem, family
def _p(lang, en, fi):
return en if lang == "en" else fi
def _stmt(lang, title, body):
return f"**{_p(lang, *title)}**\n\n{_p(lang, *body)}"
def _edges(rng, n, m, directed=False, wmax=None):
out = []
for _ in range(m):
u, v = rng.randrange(n), rng.randrange(n)
if wmax is None:
out.append([u, v])
else:
out.append([u, v, rng.randint(1, wmax)])
return out
# ----------------------------------------------------------------------------- union-find
def union_find(rng: random.Random, lang: str) -> Problem:
var = rng.choice(["components", "largest", "first_cycle"])
name = rng.choice({"components": ["count_components", "number_of_groups"], "largest": ["largest_group", "biggest_component"],
"first_cycle": ["first_redundant_edge", "first_cycle_edge"]}[var])
dsu = ''' parent = list(range(n))
size = [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
'''
if var == "components":
body = ''' groups = n
for u, v in edges:
ru, rv = find(u), find(v)
if ru != rv:
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru # union by size keeps the trees shallow
size[ru] += size[rv]
groups -= 1
return groups
'''
oracle = '''def FN(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen, groups = set(), 0
for s in range(n):
if s not in seen:
groups += 1
todo = [s]
seen.add(s)
while todo:
x = todo.pop()
for y in adj[x]:
if y not in seen:
seen.add(y)
todo.append(y)
return groups
'''
ask = ("Return the number of connected groups.", "Palauta yhtenäisten ryhmien määrä.")
ret = "int"
elif var == "largest":
body = ''' for u, v in edges:
ru, rv = find(u), find(v)
if ru != rv:
if size[ru] < size[rv]:
ru, rv = rv, ru
parent[rv] = ru # union by size keeps the trees shallow
size[ru] += size[rv]
return max(size[find(x)] for x in range(n)) if n else 0
'''
oracle = '''def FN(n, edges):
best = 0
for s in range(n):
seen = {s}
changed = True
while changed: # grow the group until no edge adds a new node
changed = False
for u, v in edges:
if (u in seen) != (v in seen):
seen |= {u, v}
changed = True
best = max(best, len(seen))