File size: 24,368 Bytes
072246b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
"""65 independent domain algorithms used by the evaluator's reference projects."""

from __future__ import annotations

import calendar
import collections
import csv
import datetime as dt
import decimal
import fnmatch
import hashlib
import heapq
import io
import itertools
import json
import math
import re
import statistics
import urllib.parse


def solve(name: str, x: dict):
    return globals()["solve_" + name](x)


def solve_word_frequency(x):
    words = re.findall(r"[a-z0-9]+", x["text"].lower())
    counts = collections.Counter(words)
    return [
        {"word": w, "count": n}
        for w, n in sorted(counts.items(), key=lambda p: (-p[1], p[0]))
    ]


def solve_slug_registry(x):
    used, out = set(), []
    for title in x["titles"]:
        root = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "item"
        slug, i = root, 2
        while slug in used:
            slug, i = f"{root}-{i}", i + 1
        used.add(slug)
        out.append(slug)
    return out


def solve_run_length(x):
    return [[char, len(list(group))] for char, group in itertools.groupby(x["text"])]


def solve_bracket_audit(x):
    stack = []
    for i, c in enumerate(x["text"]):
        if c in "([{":
            stack.append((c, i))
        elif c in ")]}":
            if not stack or "([{".index(stack[-1][0]) != ")]}".index(c):
                return {"balanced": False, "position": i}
            stack.pop()
    return {"balanced": not stack, "position": stack[-1][1] if stack else None}


def solve_text_wrap(x):
    lines, line = [], ""
    for word in x["text"].split():
        if line and len(line) + 1 + len(word) > x["width"]:
            lines.append(line)
            line = ""
        line = line + " " + word if line else word
    if line:
        lines.append(line)
    return lines


def solve_ngram_index(x):
    tokens, n = x["tokens"], x["n"]
    found = collections.defaultdict(list)
    for i in range(len(tokens) - n + 1):
        found[tuple(tokens[i : i + n])].append(i)
    return [{"tokens": list(k), "positions": found[k]} for k in sorted(found)]


def solve_glob_filter(x):
    return sorted({p for p in x["paths"] if fnmatch.fnmatchcase(p, x["pattern"])})


def solve_edit_distance(x):
    a, b = x["a"], x["b"]
    row = list(range(len(b) + 1))
    for i, char in enumerate(a, 1):
        nxt = [i]
        for j, other in enumerate(b, 1):
            nxt.append(min(nxt[-1] + 1, row[j] + 1, row[j - 1] + (char != other)))
        row = nxt
    return row[-1]


def solve_roman_codec(x):
    n, out = x["number"], ""
    for value, symbol in [
        (1000, "M"),
        (900, "CM"),
        (500, "D"),
        (400, "CD"),
        (100, "C"),
        (90, "XC"),
        (50, "L"),
        (40, "XL"),
        (10, "X"),
        (9, "IX"),
        (5, "V"),
        (4, "IV"),
        (1, "I"),
    ]:
        q, n = divmod(n, value)
        out += symbol * q
    return out


def solve_caesar_cipher(x):
    out = ""
    for c in x["text"]:
        base = ord("a") if "a" <= c <= "z" else ord("A") if "A" <= c <= "Z" else None
        out += chr((ord(c) - base + x["shift"]) % 26 + base) if base is not None else c
    return out


def solve_csv_records(x):
    rows = list(csv.reader(io.StringIO(x["csv"])))
    return [dict(zip(rows[0], row)) for row in rows[1:]] if rows else []


def solve_record_query(x):
    rows = [
        r for r in x["rows"] if all(k in r and r[k] == v for k, v in x["where"].items())
    ]
    return [{k: r.get(k) for k in x["select"]} for r in rows]


def solve_inner_join(x):
    return [
        {"left": a, "right": b}
        for a in x["left"]
        for b in x["right"]
        if x["key"] in a and x["key"] in b and a[x["key"]] == b[x["key"]]
    ]


def solve_group_totals(x):
    groups = collections.defaultdict(list)
    for row in x["rows"]:
        groups[row[x["group"]]].append(row[x["value"]])
    return [
        {"key": k, "count": len(groups[k]), "sum": sum(groups[k])}
        for k in sorted(groups)
    ]


def solve_json_flatten(x):
    out = {}

    def walk(value, path):
        if isinstance(value, dict) and value:
            for k in sorted(value):
                walk(value[k], path + "/" + k.replace("~", "~0").replace("/", "~1"))
        elif isinstance(value, list) and value:
            for i, child in enumerate(value):
                walk(child, path + "/" + str(i))
        else:
            out[path] = value

    walk(x["value"], "")
    return out


def solve_merge_patch(x):
    def merge(target, patch):
        if not isinstance(patch, dict):
            return patch
        out = dict(target) if isinstance(target, dict) else {}
        for k, v in patch.items():
            if v is None:
                out.pop(k, None)
            else:
                out[k] = merge(out.get(k), v)
        return out

    return merge(x["target"], x["patch"])


def solve_json_pointer(x):
    value = x["value"]
    if x["pointer"] == "":
        return {"found": True, "value": value}
    try:
        for token in x["pointer"][1:].split("/"):
            token = token.replace("~1", "/").replace("~0", "~")
            if isinstance(value, list):
                if not re.fullmatch(r"0|[1-9][0-9]*", token):
                    raise KeyError(token)
                value = value[int(token)]
            elif isinstance(value, dict):
                value = value[token]
            else:
                raise KeyError(token)
        return {"found": True, "value": value}
    except (KeyError, IndexError):
        return {"found": False, "value": None}


def solve_dedupe_records(x):
    seen, out = set(), []
    for row in x["rows"]:
        key = json.dumps(
            [row.get(k) for k in x["keys"]], sort_keys=True, separators=(",", ":")
        )
        if key not in seen:
            out.append(row)
            seen.add(key)
    return out


def solve_pivot_table(x):
    cells = collections.defaultdict(int)
    rows, cols = set(), set()
    for item in x["rows"]:
        r, c = item[x["row"]], item[x["column"]]
        rows.add(r)
        cols.add(c)
        cells[r, c] += item[x["value"]]
    rows, cols = sorted(rows), sorted(cols)
    return {
        "rows": rows,
        "columns": cols,
        "values": [[cells[r, c] for c in cols] for r in rows],
    }


def solve_schema_check(x):
    types = {
        "string": lambda v: isinstance(v, str),
        "integer": lambda v: type(v) is int,
        "number": lambda v: type(v) in (int, float),
        "boolean": lambda v: type(v) is bool,
        "array": lambda v: isinstance(v, list),
        "object": lambda v: isinstance(v, dict),
        "null": lambda v: v is None,
    }
    errors = []
    for key in sorted(x["schema"]):
        rule = x["schema"][key]
        if key not in x["value"]:
            if rule["required"]:
                errors.append({"field": key, "error": "required"})
        elif not types[rule["type"]](x["value"][key]):
            errors.append({"field": key, "error": "type"})
    return errors


def solve_interval_union(x):
    out = []
    for start, end in sorted(x["intervals"]):
        if out and start <= out[-1][1]:
            out[-1][1] = max(end, out[-1][1])
        else:
            out.append([start, end])
    return out


def solve_interval_gaps(x):
    low, high = x["bounds"]
    out, cursor = [], low
    for a, b in solve_interval_union(x):
        a, b = max(low, a), min(high, b)
        if a > b:
            continue
        if a > cursor:
            out.append([cursor, a])
        cursor = max(cursor, b)
    if cursor < high:
        out.append([cursor, high])
    return out


def solve_booking_peak(x):
    events = collections.defaultdict(int)
    for start, end in x["bookings"]:
        if start < end:
            events[start] += 1
            events[end] -= 1
    current = peak = 0
    at = None
    for t, delta in sorted(events.items()):
        current += delta
        if current > peak:
            peak, at = current, t
    return {"peak": peak, "at": at}


def solve_business_days(x):
    day, end = dt.date.fromisoformat(x["start"]), dt.date.fromisoformat(x["end"])
    holidays, out = set(x["holidays"]), []
    while day < end:
        if day.weekday() < 5 and day.isoformat() not in holidays:
            out.append(day.isoformat())
        day += dt.timedelta(days=1)
    return out


def solve_calendar_month(x):
    return calendar.Calendar(firstweekday=0).monthdayscalendar(x["year"], x["month"])


def solve_moving_average(x):
    return [
        sum(x["values"][i : i + x["window"]]) / x["window"]
        for i in range(len(x["values"]) - x["window"] + 1)
    ]


def solve_statistics(x):
    values = x["values"]
    if not values:
        return {
            "count": 0,
            "min": None,
            "max": None,
            "mean": None,
            "median": None,
            "variance": None,
        }
    return {
        "count": len(values),
        "min": min(values),
        "max": max(values),
        "mean": statistics.mean(values),
        "median": statistics.median(values),
        "variance": statistics.pvariance(values),
    }


def solve_histogram(x):
    edges = x["edges"]
    bins, under, over = [0] * (len(edges) - 1), 0, 0
    for v in x["values"]:
        if v < edges[0]:
            under += 1
        elif v >= edges[-1]:
            over += 1
        else:
            for i in range(len(bins)):
                if edges[i] <= v < edges[i + 1]:
                    bins[i] += 1
                    break
    return {"counts": bins, "underflow": under, "overflow": over}


def solve_matrix_product(x):
    return [
        [sum(a * b for a, b in zip(row, col)) for col in zip(*x["b"])] for row in x["a"]
    ]


def solve_polynomial(x):
    return [
        sum(c * value**i for i, c in enumerate(x["coefficients"]))
        for value in x["points"]
    ]


def solve_prime_factors(x):
    n, out, factor = x["number"], [], 2
    while factor * factor <= n:
        count = 0
        while n % factor == 0:
            n //= factor
            count += 1
        if count:
            out.append([factor, count])
        factor += 1
    if n > 1:
        out.append([n, 1])
    return out


def solve_base_convert(x):
    chars = "0123456789abcdefghijklmnopqrstuvwxyz"
    n = int(x["digits"], x["from_base"])
    sign, n = ("-" if n < 0 else ""), abs(n)
    out = ""
    while n:
        n, rem = divmod(n, x["to_base"])
        out = chars[rem] + out
    return sign + (out or "0")


def solve_money_split(x):
    weights, amount = x["weights"], x["amount"]
    total = sum(weights)
    shares = [amount * w // total for w in weights]
    order = sorted(
        range(len(weights)), key=lambda i: (-(amount * weights[i] % total), i)
    )
    for i in order[: amount - sum(shares)]:
        shares[i] += 1
    return shares


def solve_invoice_total(x):
    D = decimal.Decimal
    subtotal = sum(
        (D(item["price"]) * item["quantity"] for item in x["items"]), D(0)
    ).quantize(D(".01"), rounding=decimal.ROUND_HALF_UP)
    tax = (subtotal * D(x["tax_rate"])).quantize(
        D(".01"), rounding=decimal.ROUND_HALF_UP
    )
    return {
        "subtotal": f"{subtotal:.2f}",
        "tax": f"{tax:.2f}",
        "total": f"{subtotal + tax:.2f}",
    }


def solve_coin_change(x):
    amount, coins = x["amount"], sorted(set(x["coins"]))
    dp = [0] + [amount + 1] * amount
    for n in range(1, amount + 1):
        dp[n] = min([dp[n - c] + 1 for c in coins if c <= n] or [amount + 1])
    return None if dp[amount] > amount else dp[amount]


def graph(x, weighted=False, directed=True):
    adj = {node: [] for node in x["nodes"]}
    for edge in x["edges"]:
        a, b = edge[:2]
        adj[a].append((b, edge[2]) if weighted else b)
        if not directed:
            adj[b].append((a, edge[2]) if weighted else a)
    return adj


def solve_graph_reach(x):
    adj, found = graph(x), {x["start"]}
    todo = [x["start"]]
    while todo:
        for node in adj[todo.pop()]:
            if node not in found:
                found.add(node)
                todo.append(node)
    return sorted(found)


def solve_shortest_path(x):
    adj = graph(x, weighted=True)
    distances = {x["start"]: 0}
    queue = [(0, x["start"])]
    while queue:
        distance, node = heapq.heappop(queue)
        if distances[node] != distance:
            continue
        for other, weight in adj[node]:
            alt = distance + weight
            if alt < distances.get(other, math.inf):
                distances[other] = alt
                heapq.heappush(queue, (alt, other))
    return {node: distances.get(node) for node in sorted(x["nodes"])}


def solve_topological_order(x):
    adj, indegree = graph(x), dict.fromkeys(x["nodes"], 0)
    for edges in adj.values():
        for node in edges:
            indegree[node] += 1
    queue = [n for n in indegree if indegree[n] == 0]
    heapq.heapify(queue)
    out = []
    while queue:
        node = heapq.heappop(queue)
        out.append(node)
        for other in adj[node]:
            indegree[other] -= 1
            if indegree[other] == 0:
                heapq.heappush(queue, other)
    return out if len(out) == len(adj) else None


def solve_connected_components(x):
    adj, seen, out = graph(x, directed=False), set(), []
    for node in sorted(adj):
        if node in seen:
            continue
        group, todo = [], [node]
        seen.add(node)
        while todo:
            n = todo.pop()
            group.append(n)
            for other in adj[n]:
                if other not in seen:
                    seen.add(other)
                    todo.append(other)
        out.append(sorted(group))
    return out


def solve_grid_route(x):
    grid, start, end = x["grid"], tuple(x["start"]), tuple(x["end"])
    seen, queue = {start}, collections.deque([(start, 0)])
    if grid[start[0]][start[1]] == "#" or grid[end[0]][end[1]] == "#":
        return None
    while queue:
        (r, c), distance = queue.popleft()
        if (r, c) == end:
            return distance
        for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
            if (
                0 <= nr < len(grid)
                and 0 <= nc < len(grid[0])
                and grid[nr][nc] != "#"
                and (nr, nc) not in seen
            ):
                seen.add((nr, nc))
                queue.append(((nr, nc), distance + 1))
    return None


def solve_tree_outline(x):
    children = collections.defaultdict(list)
    for node in x["nodes"]:
        children[node["parent"]].append(node["id"])
    out = []

    def walk(parent, depth):
        for node in sorted(children[parent]):
            out.append({"id": node, "depth": depth})
            walk(node, depth + 1)

    walk(None, 0)
    return out


def solve_dependency_build(x):
    deps, out, active, done = x["dependencies"], [], set(), set()

    def visit(node):
        if node in active:
            raise ValueError("cycle")
        if node in done:
            return
        active.add(node)
        for other in sorted(deps[node]):
            visit(other)
        active.remove(node)
        done.add(node)
        out.append(node)

    try:
        for target in sorted(set(x["targets"])):
            visit(target)
    except ValueError:
        return None
    return out


def solve_path_normalize(x):
    out = []
    for path in x["paths"]:
        parts = []
        for part in path.split("/"):
            if part in ("", "."):
                continue
            if part == "..":
                if parts:
                    parts.pop()
            else:
                parts.append(part)
        out.append("/" + "/".join(parts))
    return out


def solve_url_query(x):
    out = collections.defaultdict(list)
    for k, v in urllib.parse.parse_qsl(x["query"], keep_blank_values=True):
        out[k].append(v)
    return dict(out)


def solve_version_sort(x):
    def key(v):
        core, _, pre = v.partition("-")
        parts = tuple(map(int, core.split(".")))
        ids = (
            tuple((0, int(p)) if p.isdigit() else (1, p) for p in pre.split("."))
            if pre
            else ()
        )
        return parts, not bool(pre), ids

    return sorted(x["versions"], key=key)


def solve_lru_trace(x):
    cache, hits, misses = collections.OrderedDict(), 0, 0
    for key in x["accesses"]:
        if key in cache:
            hits += 1
            cache.move_to_end(key)
        else:
            misses += 1
            if x["capacity"]:
                cache[key] = True
                if len(cache) > x["capacity"]:
                    cache.popitem(last=False)
    return {"hits": hits, "misses": misses, "keys": list(cache)}


def solve_rate_limit(x):
    history, out = collections.defaultdict(collections.deque), []
    for event in x["events"]:
        times = history[event["key"]]
        while times and times[0] <= event["time"] - x["window"]:
            times.popleft()
        allowed = len(times) < x["limit"]
        if allowed:
            times.append(event["time"])
        out.append(allowed)
    return out


def solve_priority_queue(x):
    queue, out, seq = [], [], 0
    for event in x["events"]:
        if event["op"] == "push":
            heapq.heappush(queue, (event["priority"], seq, event["value"]))
            seq += 1
        else:
            out.append(heapq.heappop(queue)[2] if queue else None)
    return {"popped": out, "remaining": [v for _, _, v in sorted(queue)]}


def solve_round_robin(x):
    quantum = x["quantum"]
    queue = collections.deque((job["id"], job["duration"]) for job in x["jobs"])
    clock, slices, completion = 0, [], {}
    while queue:
        key, left = queue.popleft()
        used = min(quantum, left)
        slices.append({"id": key, "start": clock, "end": clock + used})
        clock += used
        if left > used:
            queue.append((key, left - used))
        else:
            completion[key] = clock
    return {"slices": slices, "completion": completion}


def solve_inventory_ledger(x):
    stock, rejected = {}, []
    for i, event in enumerate(x["events"]):
        new = stock.get(event["sku"], 0) + event["delta"]
        if new < 0:
            rejected.append(i)
        else:
            stock[event["sku"]] = new
    return {"stock": stock, "rejected": rejected}


def solve_bank_ledger(x):
    balances, rejected = dict(x["balances"]), []
    for i, t in enumerate(x["transfers"]):
        if (
            t["from"] not in balances
            or t["to"] not in balances
            or balances[t["from"]] < t["amount"]
        ):
            rejected.append(i)
        else:
            balances[t["from"]] -= t["amount"]
            balances[t["to"]] += t["amount"]
    return {"balances": balances, "rejected": rejected}


def solve_ballot_count(x):
    counts = dict.fromkeys(x["candidates"], 0)
    invalid = 0
    for vote in x["votes"]:
        if vote in counts:
            counts[vote] += 1
        else:
            invalid += 1
    return {
        "ranking": [
            {"candidate": c, "votes": n}
            for c, n in sorted(counts.items(), key=lambda p: (-p[1], p[0]))
        ],
        "invalid": invalid,
    }


def solve_search_rank(x):
    terms = set(re.findall(r"[a-z0-9]+", x["query"].lower()))
    scored = []
    for doc in x["documents"]:
        counts = collections.Counter(re.findall(r"[a-z0-9]+", doc["text"].lower()))
        score = sum(counts[t] for t in terms)
        if score:
            scored.append({"id": doc["id"], "score": score})
    return sorted(scored, key=lambda r: (-r["score"], r["id"]))


def solve_log_summary(x):
    counts = collections.Counter(event["level"] for event in x["events"])
    errors = [e["message"] for e in x["events"] if e["level"] == "ERROR"]
    return {"counts": dict(counts), "errors": errors}


def solve_uptime_report(x):
    intervals = solve_interval_union(
        {
            "intervals": [
                [max(a, x["start"]), min(b, x["end"])]
                for a, b in x["downtime"]
                if max(a, x["start"]) < min(b, x["end"])
            ]
        }
    )
    down = sum(b - a for a, b in intervals)
    return {"down": down, "up": x["end"] - x["start"] - down}


def solve_segment_intersection(x):
    a, b, c, d = x["a"], x["b"], x["c"], x["d"]

    def cross(p, q, r):
        return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])

    def on(p, q, r):
        return (
            cross(p, q, r) == 0
            and min(p[0], q[0]) <= r[0] <= max(p[0], q[0])
            and min(p[1], q[1]) <= r[1] <= max(p[1], q[1])
        )

    u, v, w, z = cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)
    return (
        (u * v < 0 and w * z < 0)
        or on(a, b, c)
        or on(a, b, d)
        or on(c, d, a)
        or on(c, d, b)
    )


def solve_polygon_area(x):
    pts = x["points"]
    return (
        abs(sum(a[0] * b[1] - a[1] * b[0] for a, b in zip(pts, pts[1:] + pts[:1]))) / 2
        if pts
        else 0
    )


def solve_skyline(x):
    buildings = x["buildings"]
    points, prev = [], 0
    for t in sorted({v for a, b, _ in buildings for v in (a, b)}):
        height = max([h for a, b, h in buildings if a <= t < b] or [0])
        if height != prev:
            points.append([t, height])
            prev = height
    return points


def solve_knapsack(x):
    capacity = x["capacity"]
    dp = [0] * (capacity + 1)
    for item in x["items"]:
        for w in range(capacity, item["weight"] - 1, -1):
            dp[w] = max(dp[w], dp[w - item["weight"]] + item["value"])
    return dp[capacity]


def solve_task_selection(x):
    end, out = None, []
    for job in sorted(x["tasks"], key=lambda j: (j["end"], j["start"], j["id"])):
        if end is None or job["start"] >= end:
            out.append(job["id"])
            end = job["end"]
    return out


def solve_sequence_diff(x):
    a, b = x["a"], x["b"]
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) - 1, -1, -1):
        for j in range(len(b) - 1, -1, -1):
            dp[i][j] = (
                1 + dp[i + 1][j + 1]
                if a[i] == b[j]
                else max(dp[i + 1][j], dp[i][j + 1])
            )
    i = j = 0
    out = []
    while i < len(a) or j < len(b):
        if i < len(a) and j < len(b) and a[i] == b[j]:
            out.append(["keep", a[i]])
            i, j = i + 1, j + 1
        elif i < len(a) and (j == len(b) or dp[i + 1][j] >= dp[i][j + 1]):
            out.append(["delete", a[i]])
            i += 1
        else:
            out.append(["insert", b[j]])
            j += 1
    return out


def solve_finite_automaton(x):
    transitions = {(t["from"], t["symbol"]): t["to"] for t in x["transitions"]}
    out = []
    for word in x["words"]:
        state = x["start"]
        for symbol in word:
            state = transitions.get((state, symbol))
            if state is None:
                break
        out.append(state in x["accepting"])
    return out


def solve_content_manifest(x):
    return [
        {
            "path": path,
            "bytes": len(text.encode("utf-8")),
            "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
        }
        for path, text in sorted(x["files"].items())
    ]


def solve_cellular_automaton(x):
    cells = {tuple(p) for p in x["live"]}
    for _ in range(x["steps"]):
        neighbors = collections.Counter(
            (r + dr, c + dc)
            for r, c in cells
            for dr in (-1, 0, 1)
            for dc in (-1, 0, 1)
            if (dr, dc) != (0, 0)
        )
        cells = {p for p, n in neighbors.items() if n == 3 or n == 2 and p in cells}
    return [list(p) for p in sorted(cells)]


def solve_expression_eval(x):
    stack = []
    for token in x["tokens"]:
        if token not in ("+", "-", "*", "/"):
            stack.append(int(token))
        else:
            b, a = stack.pop(), stack.pop()
            if token == "+":
                stack.append(a + b)
            elif token == "-":
                stack.append(a - b)
            elif token == "*":
                stack.append(a * b)
            else:
                stack.append((abs(a) // abs(b)) * (-1 if (a < 0) != (b < 0) else 1))
    return stack[0]