結果

問題 No.437 cwwゲーム
ユーザー lam6er
提出日時 2025-03-20 18:39:58
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 65 ms / 2,000 ms
コード長 1,618 bytes
コンパイル時間 155 ms
コンパイル使用メモリ 82,772 KB
実行使用メモリ 73,528 KB
最終ジャッジ日時 2025-03-20 18:40:02
合計ジャッジ時間 3,573 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import defaultdict

n = input().strip()
s = list(n)
L = len(s)
if L < 3:
    print(0)
    sys.exit()

# Generate all possible valid triples (i, j, k) with i < j < k and forms a cww number
triples = []
for i in range(L):
    for j in range(i+1, L):
        for k in range(j+1, L):
            a, b, c = s[i], s[j], s[k]
            if a == b or b != c or a == '0':
                continue
            value = int(a + b + c)
            triples.append((i, j, k, value))

if not triples:
    print(0)
    sys.exit()

full_mask = (1 << L) - 1
dp = [-sys.maxsize] * (1 << L)
dp[full_mask] = 0  # Initial state: all digits available, score 0

# Group masks by the number of set bits and process them in descending order
masks_by_bits = defaultdict(list)
for mask in range(1 << L):
    cnt = bin(mask).count('1')
    masks_by_bits[cnt].append(mask)

# Sort the keys in descending order to process masks with most bits first
sorted_bit_counts = sorted(masks_by_bits.keys(), reverse=True)

for bit_count in sorted_bit_counts:
    for mask in masks_by_bits[bit_count]:
        if dp[mask] == -sys.maxsize:
            continue
        # Check all valid triples
        for i, j, k, val in triples:
            if (mask & (1 << i)) and (mask & (1 << j)) and (mask & (1 << k)):
                new_mask = mask ^ ((1 << i) | (1 << j) | (1 << k))
                if dp[new_mask] < dp[mask] + val:
                    dp[new_mask] = dp[mask] + val

# The maximum score is the maximum value in dp, or 0 if no triples were chosen
max_score = max([x for x in dp if x != -sys.maxsize] + [0])
print(max_score)
0