Skip to content

05

https://adventofcode.com/2024/day/5

我懷疑我假解這題了,先等等。

Prob1

題目

給定一堆數字需要的前後順序和一堆數字序列,檢查數字序列是否符合前面條件。

python
import sys

rules = set()
tests = []

for line in sys.stdin:
    line = line.strip()
    if '|' in line:
        rules.add(line)
    elif ',' in line:
        tests.append(line.split(','))

ans = 0
for test in tests:
    ok = True
    
    for i in range(n):
        for j in range(i + 1, n):
            rule = test[i] + '|' + test[j]
            if rule not in rules:
                ok = False
                break
        if not ok:
            break
    if ok:
        ans += int(test[n // 2])

print(ans)
python
import sys

tests = []
rules = set()

for line in sys.stdin:
    line = line.strip()
    if '|' in line:
        rules.add(line)
    elif ',' in line:
        tests.append(line.split(','))

ans = 0
for test in tests:
    ok = True
    n = len(test)
    for i in range(n):
        for j in range(i + 1, n):
            rule = test[j] + '|' + test[i]
            if rule in rules:
                test[i], test[j] = test[j], test[i]
                ok = False

    if not ok:
        ans += int(test[n // 2])


print(ans)

Changelog

Just observe 👀