結果

問題 No.297 カードの数式
ユーザー gew1fw
提出日時 2025-06-12 19:55:19
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,102 bytes
コンパイル時間 253 ms
コンパイル使用メモリ 82,344 KB
実行使用メモリ 237,516 KB
最終ジャッジ日時 2025-06-12 19:55:51
合計ジャッジ時間 2,897 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 1 TLE * 1 -- * 21
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from itertools import permutations, combinations

def main():
    input = sys.stdin.read().split()
    n = int(input[0])
    cards = input[1:n+1]
    
    digits = []
    ops = []
    for c in cards:
        if c in '+-':
            ops.append(c)
        else:
            digits.append(c)
    
    O = len(ops)
    D = len(digits)
    if O == 0:
        print(0, 0)
        return
    
    # Generate unique permutations for digits and ops
    unique_digit_perms = set(permutations(digits))
    digit_perms = [tuple(p) for p in unique_digit_perms]
    
    unique_op_perms = set(permutations(ops))
    op_perms = [tuple(p) for p in unique_op_perms]
    
    max_val = -float('inf')
    min_val = float('inf')
    
    # Precompute all possible insert positions
    insert_positions = list(combinations(range(D-1), O))
    
    for d_perm in digit_perms:
        for inserts in insert_positions:
            sorted_inserts = sorted(inserts)
            groups = []
            current = []
            pos = 0
            for i in range(len(d_perm)):
                current.append(d_perm[i])
                if pos < len(sorted_inserts) and i == sorted_inserts[pos]:
                    groups.append(''.join(current))
                    current = []
                    pos += 1
            groups.append(''.join(current))
            
            try:
                nums = [int(g) for g in groups]
            except:
                continue  # invalid if group is empty (unlikely)
            
            if len(nums) != O + 1:
                continue
            
            for op_perm in op_perms:
                current_val = nums[0]
                for i in range(O):
                    if op_perm[i] == '+':
                        current_val += nums[i+1]
                    else:
                        current_val -= nums[i+1]
                if current_val > max_val:
                    max_val = current_val
                if current_val < min_val:
                    min_val = current_val
    
    print(max_val, min_val)

if __name__ == '__main__':
    main()
0