File size: 11,787 Bytes
22c9027
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Explicit, non-executing source adapters and independent deterministic oracles.

A source adapter changes only representation / function dispatch, never expected
answers. Original input_output strings and their hashes remain in provenance.
"""
from pathlib import Path
import ast
import itertools
import json
import math
import random
import re

ROOT = Path(__file__).resolve().parents[1]
SELECTED = [5, 6, 7, 14, 25, 26, 30, 50, 51, 59]
SOURCE_SOLUTION_INDEX = {5: 0, 6: 0, 7: 0, 14: 0, 25: 1, 26: 3, 30: 0, 50: 0, 51: 0, 59: 2}
SOURCE_ENTRY = {6: 'Solution.minimum_Number', 7: 'Solution.minTime',
                14: 'Solution.findSubString', 25: 'Solution.maximumProfit',
                30: 'Solution.findPoisonedDuration'}
FINAL_ENTRY = {6: 'smallest_rearrangement', 7: 'minimum_paint_time',
               14: 'smallest_covering_window', 25: 'maximum_profit',
               30: 'total_active_time'}
SEED = 20260801


def load_row(index):
    return json.loads((ROOT / 'candidates' / f'{index:05d}.json').read_text())


def source_cases(index):
    row = load_row(index)
    test = json.loads(row['input_output'])
    if len(test['inputs']) != len(test['outputs']) or not test['inputs']:
        raise ValueError('Empty or mismatched source test arrays')
    cases = []
    for j, (raw, expected) in enumerate(zip(test['inputs'], test['outputs'])):
        case = {'id': f'source-{j:04d}', 'kind': 'source'}
        if index == 6:
            args = [ast.literal_eval(raw.split('=', 1)[1].strip())]
            answer = str(expected)
        elif index == 7:
            n = int(re.search(r'\bn\s*=\s*(\d+)', raw)[1])
            k = int(re.search(r'\bk\s*=\s*(\d+)', raw)[1])
            arr = [int(x.strip()) for x in re.search(r'\{([^}]*)\}', raw)[1].split(',')]
            if n != len(arr): raise ValueError('Bad source n')
            args, answer = [arr, n, k], int(expected)
        elif index == 14:
            args, answer = [ast.literal_eval(raw)], int(expected)
        elif index == 25:
            n = int(re.search(r'\bn\s*=\s*(\d+)', raw)[1])
            prices = ast.literal_eval(re.search(r'prices\s*=\s*(\[[^\]]*\])', raw)[1])
            if n != len(prices): raise ValueError('Bad source n')
            args, answer = [prices, n], int(expected)
        elif index == 30:
            args, answer = raw, int(expected)
        else:
            if not isinstance(raw, str) or not isinstance(expected, str):
                raise ValueError('Unrecognized stdin representation')
            case.update(mode='stdin', input=raw, expected=expected)
            cases.append(case)
            continue
        case.update(mode='call', args=args, expected=answer)
        cases.append(case)
    return cases


def final_source_cases(index):
    cases = source_cases(index)
    for case in cases:
        if index == 7:
            arr, n, k = case['args']; case['args'] = [arr, k]
        elif index == 25:
            prices, n = case['args']; case['args'] = [prices]
    return cases


def extra_cases(index):
    rng = random.Random(SEED + index)
    cases = []
    def call(args, expected, note='independent small-case oracle'):
        cases.append({'id': f'extra-{len(cases):04d}', 'kind': 'supplemental',
                      'mode': 'call', 'args': args, 'expected': expected, 'note': note})
    def stdin(text, expected, note='independent small-case oracle'):
        cases.append({'id': f'extra-{len(cases):04d}', 'kind': 'supplemental',
                      'mode': 'stdin', 'input': text, 'expected': str(expected), 'note': note})

    if index == 5:
        # Independent of multiplicative generation: repeatedly divide each integer.
        def smooth(value):
            for prime in (2, 3, 5):
                while value % prime == 0:
                    value //= prime
            return value == 1
        prefix = [0]
        for value in range(1, 2501): prefix.append(prefix[-1] + smooth(value))
        pairs = [(1,1), (2,2), (7,7), (3,8), (1,2500)]
        for _ in range(115):
            lo = rng.randint(1, 2500); hi = rng.randint(lo, 2500); pairs.append((lo,hi))
        for start in range(0, len(pairs), 20):
            part = pairs[start:start+20]
            stdin(''.join(f'{lo} {hi}\n' for lo,hi in part) + '0\n',
                  ''.join(f'{prefix[hi]-prefix[lo-1]}\n' for lo,hi in part),
                  'Trial-division oracle; up to 20 independent range queries per process')
        stdin('0\n', '', 'Empty query stream: terminator only')
    elif index == 6:
        strings = ['0', '0000', '1', '10', '1000', '111', '90900', '846903', '55010']
        strings += [''.join(rng.choice('0012349') for _ in range(rng.randint(1,7))) for _ in range(100)]
        for s in strings:
            candidates = [''.join(p) for p in set(itertools.permutations(s)) if p[0] != '0']
            call([s], min(candidates) if candidates else s, 'Enumerate all unique digit permutations; preserve all-zero strings')
        call(['9'*49999+'0'*50000+'1'], '1'+'0'*50000+'9'*49999, '100,000-digit boundary, analytically known result')
    elif index == 7:
        def brute(arr, k):
            n = len(arr); best = sum(arr)
            for mask in range(1 << (n-1)):
                if mask.bit_count()+1 > k: continue
                part, maximum = arr[0], 0
                for j in range(1,n):
                    if mask & (1 << (j-1)):
                        maximum=max(maximum,part); part=arr[j]
                    else: part+=arr[j]
                best=min(best,max(maximum,part))
            return best
        samples = [([5],1), ([5],10), ([10,20,30,40],2), ([1,100,1],2), ([9,9,9],1)]
        samples += [([rng.randint(1,25) for _ in range(rng.randint(1,8))],rng.randint(1,10)) for _ in range(100)]
        for arr,k in samples: call([arr,k],brute(arr,k),'Enumerate every contiguous partition using at most k groups')
        for k in (1,10,100000): call([[1]*100000,k],(100000+k-1)//k,'100,000 boards, closed-form balanced all-ones boundary')
    elif index == 14:
        def brute(s):
            target=set(s); best=len(s)
            for left in range(len(s)):
                for right in range(left+1,len(s)+1):
                    if set(s[left:right])==target: best=min(best,right-left)
            return best
        values=['a','aaaaa','Aa','AABBBCBBAC','aaab','GEEKSGEEKSFOR','aabcbcdbca']
        values += [''.join(rng.choice('aAbBC') for _ in range(rng.randint(1,13))) for _ in range(110)]
        for s in values: call([s],brute(s),'Enumerate all substrings and compare character sets; case-sensitive')
        call(['a'*99999+'B'],2,'100,000-character boundary with final required character')
    elif index == 25:
        def brute(prices):
            # Enumerate buy/sell/skip decisions, independent of adjacent-difference formula.
            def solve(day, holding):
                if day == len(prices): return -10**9 if holding else 0
                best=solve(day+1,holding)
                alternative=(prices[day]+solve(day+1,False)) if holding else (-prices[day]+solve(day+1,True))
                return max(best,alternative)
            return solve(0,False)
        values=[[1],[7,6,5],[1,2,3],[4,4,4],[7,1,5,3,6,4]]
        values += [[rng.randint(1,30) for _ in range(rng.randint(1,9))] for _ in range(100)]
        for prices in values: call([prices],brute(prices),'Exhaustive trading decisions with at most one held share and no fees')
        call([[1,100000]*50000],99999*50000,'100,000-day alternating boundary')
    elif index == 26:
        def brute(dolls):
            best=0
            for mask in range(1,1<<len(dolls)):
                chosen=sorted(dolls[j] for j in range(len(dolls)) if mask>>j&1)
                if all(a[0]<b[0] and a[1]<b[1] for a,b in zip(chosen,chosen[1:])):
                    best=max(best,len(chosen))
            return best
        samples=[[(1,1),(1,2)],[(1,2),(2,1)],[(1,1),(2,2)],[(1,3),(2,1),(3,2)]]
        grid=list(itertools.product(range(1,9),repeat=2))
        samples += [rng.sample(grid,rng.randint(2,8)) for _ in range(90)]
        def pack(dolls):
            cut=len(dolls)//2
            return str(cut)+'\n'+''.join(f'{h} {r}\n' for h,r in dolls[:cut])+str(len(dolls)-cut)+'\n'+''.join(f'{h} {r}\n' for h,r in dolls[cut:])+'0\n'
        for dolls in samples: stdin(pack(dolls),str(brute(dolls))+'\n','Exhaustively enumerate subsets; both height and radius must grow strictly')
        stdin(pack([(i,i) for i in range(1,201)]),'200\n','Maximum two 100-doll groups, all nestable')
        stdin(pack([(10,i) for i in range(1,201)]),'1\n','Equal heights must never chain')
    elif index == 30:
        samples=[([],0),([],7),([0],0),([1,4],2),([1,2],2),([1,1,1],4),([0,2,4],2)]
        samples += [(sorted(rng.randint(0,35) for _ in range(rng.randint(0,12))),rng.randint(0,10)) for _ in range(100)]
        for times,duration in samples:
            occupied=set()
            for t in times: occupied.update(range(t,t+duration))
            call([times,duration],len(occupied),'Union of individual integer time units, independent of adjacent-gap formula')
        call([list(range(10000)),10000000],10009999,'10,000 events and maximum duration; analytically known continuous union')
    elif index == 50:
        for n in range(2,6):
            for k in range(1,7):
                answer=sum(math.gcd(*seq) for seq in itertools.product(range(1,k+1),repeat=n))%1000000007
                stdin(f'{n} {k}\n',str(answer)+'\n','Enumerate all K^N sequences and evaluate math.gcd directly')
        stdin('100000 1\n','1\n','Maximum N, K=1 boundary')
        stdin('100000 2\n',str((pow(2,100000,1000000007)+1)%1000000007)+'\n','K=2: all tuples have gcd 1 except the all-2 tuple')
    elif index == 51:
        for _ in range(100):
            n=rng.randint(1,6); k=rng.randint(1,50)
            a=[rng.randint(0,40) for _ in range(n)]; b=[rng.randint(0,40) for _ in range(n)]
            exists=any(all(x+y>=k for x,y in zip(a,p)) for p in itertools.permutations(b))
            stdin(f'1\n{n} {k}\n'+ ' '.join(map(str,a))+'\n'+' '.join(map(str,b))+'\n',
                  'YES\n' if exists else 'NO\n','Enumerate all pairings by permuting B; keep A fixed without loss of generality')
        stdin('1\n1000 1000000000\n'+' '.join(['0']*1000)+'\n'+' '.join(['1000000000']*1000)+'\n','YES\n','Maximum n and threshold, equality boundary')
    elif index == 59:
        def naive(n):
            arr=[0]*n
            for value in range(1,n+1):
                longest=0; chosen=None; left=0
                while left<n:
                    if arr[left]: left+=1; continue
                    right=left
                    while right<n and arr[right]==0: right+=1
                    if right-left>longest: longest=right-left; chosen=(left,right)
                    left=right
                left,right=chosen; arr[(left+right-1)//2]=value
            return arr
        # Every n up to 80, grouped in one valid stdin stream.
        stdin('80\n'+''.join(f'{n}\n' for n in range(1,81)),
              ''.join(' '.join(map(str,naive(n)))+'\n' for n in range(1,81)),
              'Directly rescan all zero runs after every placement for each n=1..80')
        n=200000; intervals=[]; todo=[(0,n-1)]
        while todo:
            left,right=todo.pop(); mid=(left+right)//2
            intervals.append((-(right-left+1),left,mid))
            if left<mid: todo.append((left,mid-1))
            if mid<right: todo.append((mid+1,right))
        ans=[0]*n
        for value,(_,left,mid) in enumerate(sorted(intervals),1): ans[mid]=value
        stdin(f'1\n{n}\n',' '.join(map(str,ans))+'\n','Maximum n; independent offline interval-tree ordering rather than online heap')
    else:
        raise ValueError(index)
    return cases