-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.py
More file actions
1796 lines (1701 loc) · 97.6 KB
/
Copy pathsolver.py
File metadata and controls
1796 lines (1701 loc) · 97.6 KB
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
MISS_PENALTY = 100.0
def _get_metric(metrics, key, default):
if isinstance(metrics, dict):
return metrics.get(key, default)
return getattr(metrics, key, default)
def effective_score(metrics):
backup_count = int(_get_metric(metrics, 'backup_count', 0))
bundle_count = int(_get_metric(metrics, 'bundle_count', 0))
if backup_count == 0 and bundle_count == 0:
return float(_get_metric(metrics, 'formula_a_score', _get_metric(metrics, 'v10_score', 0.0)))
return float(_get_metric(metrics, 'v10_score', 0.0))
def formula_a_cost(row):
return row.score * row.willingness + MISS_PENALTY * row.size * (1.0 - row.willingness)
def ordered_recursive_cost(rows):
if not rows:
return 0.0
rest = MISS_PENALTY * rows[0].size
for row in reversed(rows):
rest = row.score * row.willingness + (1.0 - row.willingness) * rest
return rest
def willingness_extreme_chain_cost(rows):
if not rows:
return 0.0
asc = sorted(rows, key=lambda row: (row.willingness, row.order))
desc = sorted(rows, key=lambda row: (-row.willingness, row.order))
return 0.5 * ordered_recursive_cost(asc) + 0.5 * ordered_recursive_cost(desc)
def solution_v10_cost(chosen, table, all_tasks):
used_tasks = set()
used_primaries = set()
backup_seen = set()
role_overlap = set()
covered = set()
valid = True
total = 0.0
formula_total = 0.0
backup_count = 0
bundle_count = 0
duplicate_backup = False
for bundle, chain in chosen:
if not chain:
valid = False
continue
primary = chain[0]
primary_row = table.get((bundle, primary))
if primary_row is None:
valid = False
continue
if primary in used_primaries:
valid = False
if primary in backup_seen:
role_overlap.add(primary)
valid = False
tasks = [task.strip() for task in bundle.split(',') if task.strip()]
if any((task in used_tasks for task in tasks)):
valid = False
used_primaries.add(primary)
used_tasks.update(tasks)
covered.update(tasks)
bundle_count += 1 if primary_row.size > 1 else 0
rows = []
chain_seen = set()
for pos, courier in enumerate(chain):
if courier in chain_seen:
valid = False
chain_seen.add(courier)
row = table.get((bundle, courier))
if row is None:
valid = False
continue
rows.append(row)
if pos > 0:
if courier in backup_seen:
duplicate_backup = True
valid = False
if courier in used_primaries:
role_overlap.add(courier)
valid = False
backup_seen.add(courier)
total += willingness_extreme_chain_cost(rows)
formula_total += formula_a_cost(primary_row)
backup_count += max(0, len(chain) - 1)
uncovered = len(all_tasks - covered)
total += MISS_PENALTY * uncovered
formula_total += MISS_PENALTY * uncovered
return {'valid': valid, 'selected_lines': len(chosen), 'covered_tasks': len(covered), 'total_tasks': len(all_tasks), 'uncovered_tasks': uncovered, 'backup_count': backup_count, 'bundle_count': bundle_count, 'duplicate_backup': duplicate_backup, 'role_overlap_count': len(role_overlap), 'v10_score': total, 'formula_a_score': formula_total}
EPS = 1e-09
class Row:
pass
class CaseData:
pass
class Metrics:
pass
class ExperimentResult:
pass
def parse_input(input_text):
lines = [line.strip() for line in input_text.splitlines() if line.strip()]
start = 1 if lines and lines[0].startswith('task_id_list') else 0
table = {}
all_tasks = set()
for order, line in enumerate(lines[start:]):
parts = line.split('\t')
if len(parts) < 4:
continue
seen_tasks = set()
tasks = []
for raw_task in parts[0].split(','):
task = raw_task.strip()
if task and task not in seen_tasks:
tasks.append(task)
seen_tasks.add(task)
if not tasks:
continue
bundle = ','.join(tasks)
courier = parts[1].strip()
if not courier:
continue
try:
score = float(parts[2])
willingness = float(parts[3])
except ValueError:
continue
row = Row(bundle, courier, score, willingness, len(tasks), order)
key = (bundle, courier)
old = table.get(key)
if old is None or order < old.order:
table[key] = row
all_tasks.update(tasks)
rows_by_bundle = {}
for row in table.values():
rows_by_bundle.setdefault(row.bundle, []).append(row)
for rows in rows_by_bundle.values():
rows.sort(key=lambda row: row.order)
return CaseData(table=table, all_tasks=all_tasks, rows_by_bundle=rows_by_bundle)
def evaluate_solution_from_case(case, solution):
raw = solution_v10_cost(solution, case.table, case.all_tasks)
return Metrics(valid=bool(raw['valid']), selected_lines=int(raw['selected_lines']), covered_tasks=int(raw['covered_tasks']), total_tasks=int(raw['total_tasks']), uncovered_tasks=int(raw['uncovered_tasks']), backup_count=int(raw['backup_count']), bundle_count=int(raw['bundle_count']), duplicate_backup=bool(raw['duplicate_backup']), role_overlap_count=int(raw['role_overlap_count']), v10_score=float(raw['v10_score']), formula_a_score=float(raw['formula_a_score']))
def sanitize_solution_from_case(case, solution):
selected = []
used_tasks = set()
used_primaries = set()
for bundle, chain in solution:
if not chain:
continue
primary = chain[0]
primary_row = case.table.get((bundle, primary))
if primary_row is None or primary in used_primaries:
continue
tasks = [task.strip() for task in bundle.split(',') if task.strip()]
if not tasks or any((task in used_tasks for task in tasks)):
continue
selected.append((bundle, list(chain)))
used_primaries.add(primary)
used_tasks.update(tasks)
clean_solution = []
used_backups = set()
for bundle, chain in selected:
primary = chain[0]
clean_chain = [primary]
for courier in chain[1:]:
if courier == primary or courier in used_primaries or courier in used_backups:
continue
if (bundle, courier) not in case.table:
continue
clean_chain.append(courier)
used_backups.add(courier)
clean_solution.append((bundle, clean_chain))
return clean_solution
def _is_better(candidate, best):
if not candidate.valid:
return False
if best is None or not best.valid:
return True
cand_score = effective_score(candidate)
best_score = effective_score(best)
if abs(cand_score - best_score) > EPS:
return cand_score < best_score
if candidate.covered_tasks != best.covered_tasks:
return candidate.covered_tasks > best.covered_tasks
return candidate.selected_lines < best.selected_lines
class AutoSolverAgent:
def __init__(self, strategies, seconds=9.5, log_path=None, planner=None, rounds=1):
self.strategies = strategies
self.seconds = seconds
self.log_path = log_path
self.planner = planner
self.rounds = max(1, rounds)
def run(self, input_text, case_id=''):
case = parse_input(input_text)
deadline = time.perf_counter() + self.seconds
history = []
best = None
for round_idx in range(self.rounds):
if round_idx == 0:
active_strategies = self.strategies
elif self.planner is not None:
active_strategies = self.planner.next_strategies(case, history, deadline)
else:
active_strategies = []
if not active_strategies or time.perf_counter() >= deadline:
break
for strategy in active_strategies:
if time.perf_counter() >= deadline:
break
start = time.perf_counter()
try:
solution = strategy.solve(input_text, case, deadline, history)
solution = sanitize_solution_from_case(case, solution)
except Exception as exc:
if 'gate not matched' in str(exc):
continue
solution = []
metrics = Metrics(valid=False, selected_lines=0, covered_tasks=0, total_tasks=len(case.all_tasks), uncovered_tasks=len(case.all_tasks), backup_count=0, bundle_count=0, duplicate_backup=False, role_overlap_count=0, v10_score=MISS_PENALTY * len(case.all_tasks), formula_a_score=MISS_PENALTY * len(case.all_tasks))
elapsed_ms = int(round((time.perf_counter() - start) * 1000))
result = ExperimentResult('err', elapsed_ms, False, metrics, solution)
history.append(result)
self._log(result, case_id, round_idx)
continue
elapsed_ms = int(round((time.perf_counter() - start) * 1000))
metrics = evaluate_solution_from_case(case, solution)
accepted = _is_better(metrics, best.metrics if best else None)
result = ExperimentResult('', elapsed_ms, accepted, metrics, solution)
history.append(result)
if accepted:
best = result
self._log(result, case_id, round_idx)
if best is not None:
return best
empty_metrics = Metrics(valid=False, selected_lines=0, covered_tasks=0, total_tasks=len(case.all_tasks), uncovered_tasks=len(case.all_tasks), backup_count=0, bundle_count=0, duplicate_backup=False, role_overlap_count=0, v10_score=MISS_PENALTY * len(case.all_tasks), formula_a_score=MISS_PENALTY * len(case.all_tasks))
return ExperimentResult('none', 0, False, empty_metrics, [])
def _log(self, result, case_id, round_idx):
return
import heapq
import random
def _primary_proxy(row, fail_weight):
return row.score * row.willingness + fail_weight * MISS_PENALTY * row.size * (1.0 - row.willingness)
def _chain_cost(rows):
if not rows:
return 0.0
def ordered_cost(order):
rest = MISS_PENALTY * order[0].size
for row in reversed(order):
rest = row.score * row.willingness + (1.0 - row.willingness) * rest
return rest
asc = sorted(rows, key=lambda row: (row.willingness, row.order))
desc = sorted(rows, key=lambda row: (-row.willingness, row.order))
return 0.5 * ordered_cost(asc) + 0.5 * ordered_cost(desc)
def _visible_cost(row):
return row.score / max(row.willingness, 0.05)
def _tasks(bundle):
return set(bundle.split(','))
def _augment_backups(case, selected, backup_cap, backup_pool=24):
chains = [[row.courier] for row in selected]
if backup_cap <= 0:
return chains
used_backup_or_primary = {row.courier for row in selected}
for idx, primary_row in enumerate(selected):
base_rows = [primary_row]
base_cost = _chain_cost(base_rows)
candidates = []
for row in case.rows_by_bundle.get(primary_row.bundle, []):
if row.courier == primary_row.courier or row.courier in used_backup_or_primary:
continue
next_cost = _chain_cost(base_rows + [row])
gain = base_cost - next_cost
if gain > 1e-09:
candidates.append((next_cost, -gain, row.order, row))
candidates.sort()
for _next_cost, _neg_gain, _order, backup in candidates[:backup_pool]:
if len(chains[idx]) - 1 >= backup_cap:
break
if backup.courier in used_backup_or_primary:
continue
current_rows = [primary_row] + [case.table[primary_row.bundle, c] for c in chains[idx][1:]]
if _chain_cost(current_rows + [backup]) < _chain_cost(current_rows) - 1e-09:
chains[idx].append(backup.courier)
used_backup_or_primary.add(backup.courier)
return chains
def _rows_to_solution(case, selected, backup_cap, backup_pool=24):
chains = _augment_backups(case, selected, backup_cap, backup_pool)
return [(row.bundle, chain) for row, chain in zip(selected, chains)]
def _is_disjoint(row, used_tasks, used_primaries):
return row.courier not in used_primaries and (not _tasks(row.bundle) & used_tasks)
class GreedyStrategy:
backup_cap = 0
backup_pool = 24
def solve(self, input_text, case, deadline, history):
rows = sorted(case.table.values(), key=lambda row: (_primary_proxy(row, self.fail_weight) / row.size, _primary_proxy(row, self.fail_weight), row.order))
used_tasks = set()
used_primaries = set()
selected = []
for row in rows:
if time.perf_counter() >= deadline:
break
tasks = set(row.bundle.split(','))
if row.courier in used_primaries or tasks & used_tasks:
continue
selected.append(row)
used_primaries.add(row.courier)
used_tasks.update(tasks)
if len(used_tasks) == len(case.all_tasks):
break
return _rows_to_solution(case, selected, self.backup_cap, self.backup_pool)
class ModularStrategy:
fail_weight = 0.8
combo_bonus = 0.0
backup_cap = 0
repair_passes = 1
backup_pool = 24
def solve(self, input_text, case, deadline, history):
selected = self._select_primary(case, deadline)
if self.repair_mode in ('refill', 'replace'):
selected = self._refill(case, selected, deadline)
if self.repair_mode == 'replace':
selected = self._replace_repair(case, selected, deadline)
return _rows_to_solution(case, selected, self.backup_cap, self.backup_pool)
def _select_primary(self, case, deadline):
ordered = sorted(case.table.values(), key=self._sort_key)
used_tasks = set()
used_primaries = set()
selected = []
for row in ordered:
if time.perf_counter() >= deadline:
break
if not _is_disjoint(row, used_tasks, used_primaries):
continue
selected.append(row)
used_primaries.add(row.courier)
used_tasks.update(_tasks(row.bundle))
if len(used_tasks) == len(case.all_tasks):
break
return selected
def _sort_key(self, row):
proxy = _primary_proxy(row, self.fail_weight)
combo_adjust = self._combo_adjust(row)
if self.primary_mode == 'gain':
gain = MISS_PENALTY * row.size - proxy + combo_adjust
return (-gain, proxy / row.size, row.order)
if self.primary_mode == 'visible':
cost = _visible_cost(row) - combo_adjust
return (cost / row.size, cost, row.order)
if self.primary_mode == 'willingness':
cost = proxy - combo_adjust
return (-row.willingness, cost / row.size, row.order)
cost = proxy - combo_adjust
return (cost / row.size, cost, row.order)
def _combo_adjust(self, row):
if row.size <= 1:
return 0.0
if self.combo_mode == 'combo_bonus':
return self.combo_bonus * (row.size - 1)
if self.combo_mode == 'combo_first':
return self.combo_bonus + 4.0 * (row.size - 1)
if self.combo_mode == 'single_first':
return -abs(self.combo_bonus + 4.0) * (row.size - 1)
return 0.0
def _refill(self, case, selected, deadline):
used_tasks = set()
used_primaries = set()
for row in selected:
used_tasks.update(_tasks(row.bundle))
used_primaries.add(row.courier)
out = list(selected)
while len(used_tasks) < len(case.all_tasks) and time.perf_counter() < deadline:
uncovered = case.all_tasks - used_tasks
candidates = [row for row in case.table.values() if row.courier not in used_primaries and _tasks(row.bundle) <= uncovered]
if not candidates:
break
best = min(candidates, key=self._sort_key)
out.append(best)
used_primaries.add(best.courier)
used_tasks.update(_tasks(best.bundle))
return out
def _replace_repair(self, case, selected, deadline):
current = list(selected)
best_solution = _rows_to_solution(case, current, self.backup_cap, self.backup_pool)
best_metrics = evaluate_solution_from_case(case, best_solution)
for _pass in range(max(0, self.repair_passes)):
if time.perf_counter() >= deadline:
break
improved = False
selected_keys = {(row.bundle, row.courier) for row in current}
for candidate in sorted(case.table.values(), key=self._sort_key):
if time.perf_counter() >= deadline:
break
if (candidate.bundle, candidate.courier) in selected_keys:
continue
candidate_tasks = _tasks(candidate.bundle)
conflicts = [idx for idx, row in enumerate(current) if row.courier == candidate.courier or _tasks(row.bundle) & candidate_tasks]
if len(conflicts) != 1:
continue
trial = [row for idx, row in enumerate(current) if idx not in conflicts]
used_tasks = set()
used_primaries = set()
legal = True
for row in trial:
tasks = _tasks(row.bundle)
if row.courier in used_primaries or tasks & used_tasks:
legal = False
break
used_primaries.add(row.courier)
used_tasks.update(tasks)
if not legal or not _is_disjoint(candidate, used_tasks, used_primaries):
continue
trial.append(candidate)
trial_solution = _rows_to_solution(case, trial, self.backup_cap, self.backup_pool)
metrics = evaluate_solution_from_case(case, trial_solution)
if metrics.valid and (metrics.covered_tasks > best_metrics.covered_tasks or (metrics.covered_tasks == best_metrics.covered_tasks and metrics.v10_score + 1e-09 < best_metrics.v10_score)):
current = trial
best_metrics = metrics
improved = True
break
if not improved:
break
return current
class RemoveRefillStrategy:
fail_weight = 0.8
remove_count = 2
rounds = 2
backup_cap = 1
def solve(self, input_text, case, deadline, history):
base = ModularStrategy('proxy', 'combo_bonus', 'replace', self.fail_weight, 8.0, self.backup_cap, 1)
current_solution = base.solve(input_text, case, deadline, history)
current_rows = [case.table[bundle, chain[0]] for bundle, chain in current_solution if chain and (bundle, chain[0]) in case.table]
best_solution = current_solution
best_metrics = evaluate_solution_from_case(case, best_solution)
for _round in range(max(0, self.rounds)):
if time.perf_counter() >= deadline:
break
ranked = sorted(current_rows, key=lambda row: _primary_proxy(row, self.fail_weight), reverse=True)
kept = [row for row in current_rows if row not in set(ranked[:self.remove_count])]
trial = self._refill(case, kept, deadline)
trial_solution = _rows_to_solution(case, trial, self.backup_cap)
metrics = evaluate_solution_from_case(case, trial_solution)
if metrics.valid and (metrics.covered_tasks > best_metrics.covered_tasks or (metrics.covered_tasks == best_metrics.covered_tasks and effective_score(metrics) < effective_score(best_metrics) - 1e-09)):
current_rows = trial
best_solution = trial_solution
best_metrics = metrics
else:
break
return best_solution
def _refill(self, case, selected, deadline):
out = list(selected)
used_tasks = set()
used_couriers = set()
for row in out:
used_tasks.update(_tasks(row.bundle))
used_couriers.add(row.courier)
rows = sorted(case.table.values(), key=lambda row: (_primary_proxy(row, self.fail_weight) / row.size, _primary_proxy(row, self.fail_weight), row.order))
for row in rows:
if time.perf_counter() >= deadline or len(used_tasks) == len(case.all_tasks):
break
if _is_disjoint(row, used_tasks, used_couriers):
out.append(row)
used_tasks.update(_tasks(row.bundle))
used_couriers.add(row.courier)
return out
class GlobalBackupStrategy:
fail_weight = 0.8
backup_cap = 1
pool_per_line = 16
def solve(self, input_text, case, deadline, history):
primary_strategy = ModularStrategy('proxy', 'combo_bonus', 'refill', self.fail_weight, 8.0, 0, 1)
primary_solution = primary_strategy.solve(input_text, case, deadline, history)
selected = [case.table[bundle, chain[0]] for bundle, chain in primary_solution if chain and (bundle, chain[0]) in case.table]
chains = [[row.courier] for row in selected]
used = {row.courier for row in selected}
moves = []
for idx, row in enumerate(selected):
if time.perf_counter() >= deadline:
break
base_cost = _chain_cost([row])
scored = []
for backup in case.rows_by_bundle.get(row.bundle, []):
if backup.courier == row.courier or backup.courier in used:
continue
new_cost = _chain_cost([row, backup])
gain = base_cost - new_cost
if gain > 1e-09:
scored.append((-gain, new_cost, backup.order, idx, backup))
scored.sort()
moves.extend(scored[:self.pool_per_line])
moves.sort()
for _neg_gain, _new_cost, _order, idx, backup in moves:
if time.perf_counter() >= deadline:
break
if backup.courier in used or len(chains[idx]) - 1 >= self.backup_cap:
continue
chains[idx].append(backup.courier)
used.add(backup.courier)
return [(row.bundle, chain) for row, chain in zip(selected, chains)]
class ExperienceOperatorStrategy:
primary_mode = 'proxy'
combo_mode = 'combo_bonus'
repair_mode = 'replace'
fail_weight = 0.8
combo_bonus = 8.0
backup_cap = 1
repair_passes = 1
backup_pool = 24
operation_cap = 120
def solve(self, input_text, case, deadline, history):
if not self._matches_case(case):
raise RuntimeError('experience operator gate not matched')
if self.operator == 'global_backup_chain':
return GlobalBackupStrategy(fail_weight=self.fail_weight, backup_cap=max(1, self.backup_cap), pool_per_line=max(4, min(32, self.backup_pool))).solve(input_text, case, deadline, history)
if self.operator == 'high_noise_backup_chain':
return self._backup_chain_local_search(input_text, case, deadline, history, max_len=max(2, min(3, self.backup_cap + 1)))
if self.operator == 'high_noise_chain_refill':
base = self._backup_chain_local_search(input_text, case, deadline, history, max_len=max(2, min(4, self.backup_cap + 1)))
return self._bounded_refill(case, base, deadline)
if self.operator == 'tiny_exact_v10':
return self._tiny_exact_v10(case, deadline)
if self.operator == 'small_combo_shift_backup20':
return self._small_combo_shift_backup20(case, deadline)
if self.operator == 'small_task15_shift2_backup20' and len(case.all_tasks) == 15:
base = ModularStrategy('proxy', 'combo_bonus', 'replace', self.fail_weight, self.combo_bonus, max(1, self.backup_cap), 1, 20)
return base.solve(input_text, case, deadline, history)
if self.operator == 'low_w_o1_primary_swap':
return self._low_w_o1_primary_swap(input_text, case, deadline, history)
if self.operator == 'scarce_coverage_first':
base = ModularStrategy('gain', 'single_first', 'refill', max(self.fail_weight, 1.1), self.combo_bonus, 0, 1, self.backup_pool)
return base.solve(input_text, case, deadline, history)
if self.operator == 'medium_timeout_guard':
base = ModularStrategy(self.primary_mode, self.combo_mode, 'refill', self.fail_weight, self.combo_bonus, min(1, self.backup_cap), 1, self.backup_pool)
return base.solve(input_text, case, deadline, history)
if self.operator == 'scarce_courier_beam':
return self._scarce_courier_beam_search(case, deadline, beam_width=max(80, min(2600, self.operation_cap * 18)), candidate_limit=max(16, min(90, self.backup_pool * 6)))
if self.operator == 'scarce_set_packing_search':
return self._beam_primary_search(case, deadline, beam_width=max(24, min(120, self.operation_cap)), row_limit=1800, coverage_first=True, backup_cap=0)
if self.operator == 'large_combo_beam_search':
return self._beam_primary_search(case, deadline, beam_width=max(24, min(140, self.operation_cap)), row_limit=2200, coverage_first=False, backup_cap=self.backup_cap)
if self.operator == 'large_combo_primary_repair':
return self._large_combo_primary_repair(input_text, case, deadline, history)
if self.operator == 'combo_primary_backup_joint_search':
return self._combo_primary_backup_joint_search(input_text, case, deadline, history)
if self.operator == 'backup_chain_local_search':
return self._backup_chain_local_search(input_text, case, deadline, history, max_len=max(2, min(4, self.backup_cap + 1)))
if self.operator == 'primary_swap_k2':
return RemoveRefillStrategy(fail_weight=self.fail_weight, remove_count=2, rounds=max(1, min(3, self.repair_passes)), backup_cap=self.backup_cap).solve(input_text, case, deadline, history)
if self.operator == 'case_gap_driven_local_search':
task_count = len(case.all_tasks)
if task_count:
courier_count = len({courier for _bundle, courier in case.table})
if task_count >= 40 and courier_count <= int(task_count * 1.2):
return self._beam_primary_search(case, deadline, beam_width=max(32, min(120, self.operation_cap)), row_limit=1800, coverage_first=True, backup_cap=0)
if task_count >= 40:
return self._beam_primary_search(case, deadline, beam_width=max(32, min(140, self.operation_cap)), row_limit=2200, coverage_first=False, backup_cap=self.backup_cap)
return RemoveRefillStrategy(self.fail_weight, 2, 2, self.backup_cap).solve(input_text, case, deadline, history)
if self.operator == 'case_expert_router':
return self._case_expert_router(input_text, case, deadline, history)
base = ModularStrategy(self.primary_mode, self.combo_mode, self.repair_mode, self.fail_weight, self.combo_bonus, self.backup_cap, self.repair_passes, self.backup_pool)
return base.solve(input_text, case, deadline, history)
def _matches_case(self, case):
task_count = len(case.all_tasks)
courier_count = len({courier for _bundle, courier in case.table})
willingness = [row.willingness for row in case.table.values()]
scores = [row.score for row in case.table.values()]
avg_w = sum(willingness) / max(1, len(willingness))
var_w = sum(((w - avg_w) ** 2 for w in willingness)) / max(1, len(willingness))
avg_score = sum(scores) / max(1, len(scores))
if self.operator == 'global_backup_chain':
return True
if self.operator == 'backup_chain_local_search':
return task_count >= 15
if self.operator == 'primary_swap_k2':
return task_count >= 15
if self.operator == 'case_gap_driven_local_search':
return task_count >= 15
if self.operator == 'case_expert_router':
return True
if self.operator == 'scarce_set_packing_search':
return task_count >= 30 and courier_count <= int(task_count * 1.2)
if self.operator == 'large_combo_beam_search':
return task_count >= 40 and courier_count > int(task_count * 1.2)
if self.operator == 'large_combo_primary_repair':
return task_count >= 40 and courier_count > int(task_count * 1.2)
if self.operator == 'combo_primary_backup_joint_search':
return task_count >= 15 and courier_count > int(task_count * 1.2)
if self.operator == 'small_task15_shift2_backup20':
return task_count == 15
if self.operator == 'small_combo_shift_backup20':
return task_count == 15 and (not courier_count <= int(task_count * 1.2))
if self.operator == 'tiny_exact_v10':
return 0 < task_count <= 6 and (not courier_count <= int(task_count * 1.2))
if self.operator == 'low_w_o1_primary_swap':
return task_count == 30 and avg_w <= 0.22 and (avg_score <= 35.0)
if self.operator == 'scarce_coverage_first':
return task_count >= 30 and courier_count <= int(task_count * 1.2)
if self.operator == 'scarce_courier_beam':
return task_count >= 30 and courier_count <= int(task_count * 1.2)
if self.operator == 'medium_timeout_guard':
return task_count == 30 and avg_score >= 45.0 and (var_w < 0.035)
if self.operator == 'high_noise_backup_chain':
return task_count == 30 and avg_score < 45.0 and (avg_w > 0.22)
if self.operator == 'high_noise_chain_refill':
return task_count == 30 and avg_score < 45.0 and (avg_w > 0.22)
return False
def _case_expert_router(self, input_text, case, deadline, history):
task_count = len(case.all_tasks)
courier_count = len({courier for _bundle, courier in case.table})
values = list(case.table.values())
if not values:
return []
avg_score = sum((row.score for row in values)) / max(1, len(values))
avg_w = sum((row.willingness for row in values)) / max(1, len(values))
bundle_ratio = sum((1 for row in values if row.size > 1)) / max(1, len(values))
sparse = task_count >= 30 and courier_count <= int(max(1, task_count) * 1.2)
candidates = []
def add(strategy):
candidates.append(strategy)
if task_count <= 6 and (not sparse):
add(ExperienceOperatorStrategy('tiny_exact_v10', fail_weight=0.55, combo_mode='combo_first', combo_bonus=4.0, backup_cap=2, backup_pool=10, operation_cap=120))
add(ModularStrategy('proxy', 'combo_first', 'replace', 0.55, 8.0, 2, 2, 10))
elif task_count == 15 and (not sparse):
add(ExperienceOperatorStrategy('small_combo_shift_backup20', fail_weight=0.55, combo_mode='combo_first', combo_bonus=max(8.0, self.combo_bonus), backup_cap=1, backup_pool=20, operation_cap=max(128, self.operation_cap)))
add(ExperienceOperatorStrategy('backup_chain_local_search', fail_weight=0.55, combo_mode='combo_first', combo_bonus=6.0, repair_mode='refill', backup_cap=2, backup_pool=20, repair_passes=2, operation_cap=80))
elif sparse:
add(ExperienceOperatorStrategy('scarce_courier_beam', primary_mode='gain', combo_mode='single_first', repair_mode='refill', fail_weight=max(0.95, self.fail_weight), combo_bonus=max(4.0, self.combo_bonus), backup_cap=0, backup_pool=12, operation_cap=max(140, self.operation_cap)))
add(ExperienceOperatorStrategy('scarce_set_packing_search', primary_mode='gain', combo_mode='single_first', repair_mode='refill', fail_weight=max(0.9, self.fail_weight), combo_bonus=max(4.0, self.combo_bonus), backup_cap=0, backup_pool=8, operation_cap=max(120, self.operation_cap)))
add(ExperienceOperatorStrategy('scarce_coverage_first', primary_mode='gain', combo_mode='single_first', repair_mode='refill', fail_weight=max(1.05, self.fail_weight), combo_bonus=max(4.0, self.combo_bonus), backup_cap=0, backup_pool=8, operation_cap=72))
add(ExperienceOperatorStrategy('case_gap_driven_local_search', primary_mode='gain', combo_mode='single_first', repair_mode='refill', fail_weight=max(0.85, self.fail_weight), combo_bonus=max(4.0, self.combo_bonus), backup_cap=0, backup_pool=8, operation_cap=max(120, self.operation_cap)))
elif task_count >= 40:
add(ExperienceOperatorStrategy('combo_primary_backup_joint_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='replace', fail_weight=0.55, combo_bonus=max(8.0, self.combo_bonus), backup_cap=1, backup_pool=max(20, self.backup_pool), repair_passes=2, operation_cap=max(180, self.operation_cap)))
add(GlobalBackupStrategy(fail_weight=0.95, backup_cap=2, pool_per_line=max(12, min(32, self.backup_pool))))
add(GlobalBackupStrategy(fail_weight=0.75, backup_cap=2, pool_per_line=max(12, min(32, self.backup_pool))))
add(ExperienceOperatorStrategy('backup_chain_local_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.55, combo_bonus=max(4.0, self.combo_bonus), backup_cap=2, backup_pool=max(16, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
add(ExperienceOperatorStrategy('primary_swap_k2', primary_mode='proxy', combo_mode='combo_bonus', repair_mode='replace', fail_weight=0.65, combo_bonus=max(6.0, self.combo_bonus), backup_cap=1, backup_pool=max(12, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
if bundle_ratio > 0.5:
add(ExperienceOperatorStrategy('large_combo_beam_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.55, combo_bonus=max(6.0, self.combo_bonus), backup_cap=1, backup_pool=max(12, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
elif task_count == 30 and avg_w <= 0.22 and (avg_score <= 35.0):
add(GlobalBackupStrategy(fail_weight=0.95, backup_cap=2, pool_per_line=max(12, min(32, self.backup_pool))))
add(ExperienceOperatorStrategy('low_w_o1_primary_swap', primary_mode='proxy', combo_mode='combo_bonus', repair_mode='replace', fail_weight=0.65, combo_bonus=max(6.0, self.combo_bonus), backup_cap=1, backup_pool=max(12, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
add(ExperienceOperatorStrategy('backup_chain_local_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.65, combo_bonus=4.0, backup_cap=2, backup_pool=max(16, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
elif task_count == 30 and avg_score < 45.0 and (avg_w > 0.22):
add(ExperienceOperatorStrategy('high_noise_chain_refill', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.45, combo_bonus=4.0, backup_cap=2, backup_pool=max(20, self.backup_pool), repair_passes=2, operation_cap=max(160, self.operation_cap)))
add(ExperienceOperatorStrategy('backup_chain_local_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.45, combo_bonus=4.0, backup_cap=2, backup_pool=max(20, self.backup_pool), repair_passes=2, operation_cap=max(128, self.operation_cap)))
add(RemoveRefillStrategy(fail_weight=0.75, remove_count=2, rounds=2, backup_cap=1))
elif task_count == 30:
add(ExperienceOperatorStrategy('backup_chain_local_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=0.55, combo_bonus=max(4.0, self.combo_bonus), backup_cap=2, backup_pool=max(16, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
add(ExperienceOperatorStrategy('primary_swap_k2', primary_mode='proxy', combo_mode='combo_bonus', repair_mode='replace', fail_weight=0.65, combo_bonus=max(6.0, self.combo_bonus), backup_cap=1, backup_pool=max(12, self.backup_pool), repair_passes=2, operation_cap=max(96, self.operation_cap)))
add(RemoveRefillStrategy(fail_weight=0.75, remove_count=2, rounds=2, backup_cap=1))
add(GlobalBackupStrategy(fail_weight=0.95, backup_cap=2, pool_per_line=max(12, min(32, self.backup_pool))))
else:
add(ExperienceOperatorStrategy('backup_chain_local_search', primary_mode='proxy', combo_mode='combo_first', repair_mode='refill', fail_weight=max(0.45, self.fail_weight), combo_bonus=self.combo_bonus, backup_cap=max(1, min(3, self.backup_cap)), backup_pool=self.backup_pool, repair_passes=2, operation_cap=self.operation_cap))
add(ModularStrategy('proxy', 'combo_bonus', 'replace', max(0.45, self.fail_weight), self.combo_bonus, max(0, min(2, self.backup_cap)), 2, self.backup_pool))
best_solution = []
best_metrics = None
for strategy in candidates:
if time.perf_counter() >= deadline:
break
try:
solution = strategy.solve(input_text, case, deadline, history)
metrics = evaluate_solution_from_case(case, solution)
except Exception:
continue
if metrics.valid and (best_metrics is None or metrics.covered_tasks > best_metrics.covered_tasks or (metrics.covered_tasks == best_metrics.covered_tasks and effective_score(metrics) < effective_score(best_metrics) - 1e-09)):
best_solution = solution
best_metrics = metrics
return best_solution
def _low_w_o1_primary_swap(self, input_text, case, deadline, history):
base = ModularStrategy(self.primary_mode, self.combo_mode, self.repair_mode, self.fail_weight, self.combo_bonus, self.backup_cap, 1, self.backup_pool)
current_solution = base.solve(input_text, case, deadline, history)
current_rows = [case.table[bundle, chain[0]] for bundle, chain in current_solution if chain and (bundle, chain[0]) in case.table]
best_solution = current_solution
best_metrics = evaluate_solution_from_case(case, best_solution)
used_keys = {(row.bundle, row.courier) for row in current_rows}
candidates = sorted(case.table.values(), key=base._sort_key)[:max(12, min(240, self.operation_cap))]
for candidate in candidates:
if time.perf_counter() >= deadline:
break
if (candidate.bundle, candidate.courier) in used_keys:
continue
candidate_tasks = _tasks(candidate.bundle)
conflicts = [idx for idx, row in enumerate(current_rows) if row.courier == candidate.courier or _tasks(row.bundle) & candidate_tasks]
if len(conflicts) != 1:
continue
trial = [row for idx, row in enumerate(current_rows) if idx not in conflicts]
used_tasks = set()
used_couriers = set()
legal = True
for row in trial:
row_tasks = _tasks(row.bundle)
if row.courier in used_couriers or row_tasks & used_tasks:
legal = False
break
used_couriers.add(row.courier)
used_tasks.update(row_tasks)
if not legal or not _is_disjoint(candidate, used_tasks, used_couriers):
continue
trial.append(candidate)
trial_solution = _rows_to_solution(case, trial, self.backup_cap, self.backup_pool)
metrics = evaluate_solution_from_case(case, trial_solution)
if metrics.valid and effective_score(metrics) + 1e-09 < effective_score(best_metrics):
best_solution = trial_solution
best_metrics = metrics
break
return best_solution
def _large_combo_primary_repair(self, input_text, case, deadline, history):
base = GreedyStrategy(fail_weight=0.45, backup_cap=max(1, self.backup_cap), backup_pool=max(16, self.backup_pool))
current_solution = base.solve(input_text, case, deadline, history)
current_rows = [case.table[bundle, chain[0]] for bundle, chain in current_solution if chain and (bundle, chain[0]) in case.table]
best_solution = current_solution
best_metrics = evaluate_solution_from_case(case, best_solution)
if not current_rows or best_metrics.covered_tasks < len(case.all_tasks):
fallback = ModularStrategy('proxy', 'combo_bonus', 'replace', self.fail_weight, self.combo_bonus, max(1, self.backup_cap), 2, self.backup_pool)
return fallback.solve(input_text, case, deadline, history)
def row_value(row):
proxy = _primary_proxy(row, self.fail_weight)
return proxy / max(1, row.size) - self.combo_bonus * max(0, row.size - 1)
candidates = [row for row in case.table.values() if row.size == 2]
candidates.sort(key=lambda row: (row_value(row), _chain_cost([row]) / max(1, row.size), row.order))
candidates = candidates[:max(80, min(900, self.operation_cap * 5))]
def rows_to_keyed(rows):
return {(row.bundle, row.courier): row for row in rows}
current_by_key = rows_to_keyed(current_rows)
for seed, candidate in enumerate(candidates):
if time.perf_counter() >= deadline:
break
candidate_tasks = _tasks(candidate.bundle)
conflicts = [row for row in current_rows if row.courier == candidate.courier or _tasks(row.bundle) & candidate_tasks]
if len(conflicts) != 2:
continue
conflict_tasks = set()
for row in conflicts:
conflict_tasks.update(_tasks(row.bundle))
if conflict_tasks != candidate_tasks:
continue
trial = [row for row in current_rows if row not in conflicts]
used_tasks = set()
used_couriers = set()
legal = True
for row in trial:
row_tasks = _tasks(row.bundle)
if row.courier in used_couriers or row_tasks & used_tasks:
legal = False
break
used_couriers.add(row.courier)
used_tasks.update(row_tasks)
if not legal or not _is_disjoint(candidate, used_tasks, used_couriers):
continue
trial.append(candidate)
if len(used_tasks | candidate_tasks) < len(case.all_tasks):
uncovered = case.all_tasks - (used_tasks | candidate_tasks)
refill = [row for row in case.table.values() if row.courier not in used_couriers and _tasks(row.bundle) <= uncovered]
refill.sort(key=lambda row: (_primary_proxy(row, self.fail_weight) / max(1, row.size), _primary_proxy(row, self.fail_weight), row.order))
for row in refill:
if time.perf_counter() >= deadline:
break
if _is_disjoint(row, used_tasks | candidate_tasks, used_couriers | {candidate.courier}):
trial.append(row)
used_tasks.update(_tasks(row.bundle))
used_couriers.add(row.courier)
if len(used_tasks | candidate_tasks) == len(case.all_tasks):
break
trial_solution = _rows_to_solution(case, trial, max(1, self.backup_cap), max(16, self.backup_pool))
metrics = evaluate_solution_from_case(case, trial_solution)
if not metrics.valid or metrics.covered_tasks < len(case.all_tasks):
continue
if effective_score(metrics) + 1e-09 < effective_score(best_metrics):
best_solution = trial_solution
best_metrics = metrics
current_rows = [case.table[bundle, chain[0]] for bundle, chain in best_solution if chain and (bundle, chain[0]) in case.table]
current_by_key = rows_to_keyed(current_rows)
if metrics.bundle_count >= max(1, min(4, self.repair_passes)):
break
return best_solution
def _combo_primary_backup_joint_search(self, input_text, case, deadline, history):
def add_global_backups(selected):
chains = [[row.courier] for row in selected]
if self.backup_cap <= 0:
return [(row.bundle, chain) for row, chain in zip(selected, chains)]
primary_used = {row.courier for row in selected}
used = set(primary_used)
moves = []
for idx, primary in enumerate(selected):
rows = case.rows_by_bundle.get(primary.bundle, [])
base_cost = _chain_cost([primary])
scored = []
for backup in rows:
if backup.courier == primary.courier or backup.courier in primary_used:
continue
c2 = _chain_cost([primary, backup])
gain = base_cost - c2
if gain > 1e-09:
scored.append((-gain, c2, -backup.willingness, backup.score, backup.order, idx, backup.courier))
scored.sort()
moves.extend(scored[:max(8, min(80, self.backup_pool * 2))])
moves.sort()
for _neg_gain, _c2, _w, _score, _order, idx, courier in moves:
if courier in used or len(chains[idx]) > max(1, self.backup_cap):
continue
chains[idx].append(courier)
used.add(courier)
return [(row.bundle, chain) for row, chain in zip(selected, chains)]
base_candidates = [GreedyStrategy(fail_weight=0.45, backup_cap=max(1, self.backup_cap), backup_pool=max(16, self.backup_pool)).solve(input_text, case, deadline, history), GreedyStrategy(fail_weight=0.85, backup_cap=0, backup_pool=max(16, self.backup_pool)).solve(input_text, case, deadline, history), ModularStrategy('proxy', 'combo_bonus', 'replace', max(0.55, self.fail_weight), max(6.0, self.combo_bonus), 0, 2, max(16, self.backup_pool)).solve(input_text, case, deadline, history)]
best_solution = []
best_metrics = None
for solution in base_candidates:
metrics = evaluate_solution_from_case(case, solution)
if metrics.valid and (best_metrics is None or metrics.covered_tasks > best_metrics.covered_tasks or (metrics.covered_tasks == best_metrics.covered_tasks and effective_score(metrics) < effective_score(best_metrics) - 1e-09)):
best_solution = solution
best_metrics = metrics
if best_metrics is None:
return best_solution
tasks = sorted(case.all_tasks)
if not tasks:
return best_solution
task_idx = {task: idx for idx, task in enumerate(tasks)}
couriers = sorted({courier for _bundle, courier in case.table})
courier_idx = {courier: idx for idx, courier in enumerate(couriers)}
full_mask = (1 << len(tasks)) - 1
def popcount(value):
return bin(value).count('1')
def single_task_assignment():
if not all((task in case.rows_by_bundle for task in tasks)):
return []
node_count = 1 + len(tasks) + len(couriers) + 1
source = 0
sink = node_count - 1
graph = [[] for _ in range(node_count)]
def add_edge(src, dst, cap, cost, row=None):
graph[src].append([dst, cap, cost, len(graph[dst]), row])
graph[dst].append([src, 0, -cost, len(graph[src]) - 1, None])
for idx in range(len(tasks)):
add_edge(source, 1 + idx, 1, 0.0)
for idx, courier in enumerate(couriers):
add_edge(1 + len(tasks) + idx, sink, 1, 0.0)
for task_pos, task in enumerate(tasks):
for row in case.rows_by_bundle.get(task, []):
cost = row.score * row.willingness + MISS_PENALTY * (1.0 - row.willingness)
add_edge(1 + task_pos, 1 + len(tasks) + courier_idx[row.courier], 1, cost, row)
flow = 0
potential = [0.0] * node_count
while flow < len(tasks) and time.perf_counter() < deadline:
dist = [1e+18] * node_count
prev = [None] * node_count
dist[source] = 0.0
heap = [(0.0, source)]
while heap:
current_dist, node = heapq.heappop(heap)
if current_dist != dist[node]:
continue
for edge_idx, edge in enumerate(graph[node]):
if edge[1] <= 0:
continue
next_dist = current_dist + edge[2] + potential[node] - potential[edge[0]]
if next_dist < dist[edge[0]]:
dist[edge[0]] = next_dist
prev[edge[0]] = (node, edge_idx)
heapq.heappush(heap, (next_dist, edge[0]))
if prev[sink] is None:
break
for idx, value in enumerate(dist):
if value < 1e+18:
potential[idx] += value
node = sink
while node != source:
prev_node, edge_idx = prev[node]
edge = graph[prev_node][edge_idx]
edge[1] -= 1
graph[node][edge[3]][1] += 1
node = prev_node
flow += 1
if flow < len(tasks):
return []
rows = []
for task_pos in range(len(tasks)):
for edge in graph[1 + task_pos]:
if edge[4] is not None and edge[1] == 0:
rows.append(edge[4])
break
return rows if len(rows) == len(tasks) else []
assigned = single_task_assignment()
if assigned:
assigned_solution = add_global_backups(assigned)
assigned_metrics = evaluate_solution_from_case(case, assigned_solution)
if assigned_metrics.valid and effective_score(assigned_metrics) + 1e-09 < effective_score(best_metrics):
best_solution = assigned_solution
best_metrics = assigned_metrics
def row_profit(row):
visible_profit = row.size * MISS_PENALTY - _visible_cost(row)
risk_profit = row.size * MISS_PENALTY * row.willingness - row.score
combo = self.combo_bonus * max(0, row.size - 1)
return 0.55 * visible_profit + 0.45 * risk_profit + combo
candidates = []
by_pair = {}
next_idx = 0
for bundle, rows in case.rows_by_bundle.items():
if time.perf_counter() >= deadline:
break
bundle_tasks = _tasks(bundle)
if not bundle_tasks or len(bundle_tasks) > (2 if len(tasks) >= 20 else 3):
continue
task_mask = 0
for task in bundle_tasks:
task_mask |= 1 << task_idx[task]
for row in rows:
profit = row_profit(row)
if profit < -45.0:
continue
item = (next_idx, task_mask, 1 << courier_idx[row.courier], row, profit)
candidates.append(item)
by_pair[row.bundle, row.courier] = item
next_idx += 1
if not candidates:
return best_solution
by_task = [[] for _ in tasks]
for item in candidates:
_idx, task_mask, _role, row, profit = item
for idx in range(len(tasks)):
if task_mask >> idx & 1:
by_task[idx].append(item)
for idx, bucket in enumerate(by_task):
keep = {}
for ordering in (sorted(bucket, key=lambda x: x[4], reverse=True), sorted(bucket, key=lambda x: _visible_cost(x[3])), sorted(bucket, key=lambda x: _primary_proxy(x[3], max(0.45, self.fail_weight)) / max(1, x[3].size)), sorted(bucket, key=lambda x: x[3].willingness, reverse=True)):
for item in ordering[:max(10, min(70, self.backup_pool * 3))]:
keep[item[0]] = item
by_task[idx] = sorted(keep.values(), key=lambda x: x[4], reverse=True)[:max(30, min(90, self.operation_cap // 2))]
def exact_refill(fixed, local_deadline):
fixed_tasks = 0
fixed_roles = 0
for _idx, mask, role, _row, _profit in fixed:
fixed_tasks |= mask
fixed_roles |= role
free_mask = full_mask & ~fixed_tasks
memo = {}
def rec(remaining, roles):
if time.perf_counter() >= local_deadline:
raise TimeoutError
if remaining == 0:
return (0.0, ())
key = (remaining, roles)
if key in memo:
return memo[key]
bit = remaining & -remaining
first = bit.bit_length() - 1
best_value, best_tuple = rec(remaining & ~bit, roles)
for item in by_task[first]:
_idx, mask, role, _row, profit = item
if mask & ~remaining or role & roles:
continue
value, chosen = rec(remaining & ~mask, roles | role)