結果

問題 No.775 tatyamと素数大富豪(hard)
ユーザー gew1fw
提出日時 2025-06-12 15:41:16
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,042 bytes
コンパイル時間 179 ms
コンパイル使用メモリ 82,284 KB
実行使用メモリ 102,604 KB
最終ジャッジ日時 2025-06-12 15:41:23
合計ジャッジ時間 5,568 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 9 TLE * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

import heapq

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    
    n = int(data[0])
    k = int(data[1])
    a = data[2:2+n]
    
    # Convert each number to its string representation
    str_list = a
    
    # Convert each string to a tuple of ASCII values
    str_tuples = [tuple(ord(c) for c in s) for s in str_list]
    
    heap = []
    visited = set()
    
    for i in range(n):
        current_tuple = str_tuples[i]
        remaining = []
        for j in range(n):
            if j != i:
                remaining.append(str_tuples[j])
        # Sort the remaining tuples lexicographically
        remaining_sorted = tuple(sorted(remaining))
        # Create the heap element with negative ASCII values
        heap_element = tuple(-x for x in current_tuple)
        state = (heap_element, remaining_sorted)
        if state not in visited:
            heapq.heappush(heap, (heap_element, remaining_sorted))
            visited.add(state)
    
    results = []
    
    while len(results) < k and heap:
        current_neg_tuple, remaining = heapq.heappop(heap)
        current_tuple = tuple(-x for x in current_neg_tuple)
        
        if not remaining:
            s = ''.join(chr(c) for c in current_tuple)
            results.append(s)
            if len(results) == k:
                break
        else:
            for i in range(len(remaining)):
                next_tuple = remaining[i]
                new_tuple = current_tuple + next_tuple
                new_remaining = list(remaining)
                del new_remaining[i]
                new_remaining_sorted = tuple(sorted(new_remaining))
                
                new_neg_tuple = tuple(-x for x in new_tuple)
                state = (new_neg_tuple, new_remaining_sorted)
                if state not in visited:
                    heapq.heappush(heap, (new_neg_tuple, new_remaining_sorted))
                    visited.add(state)
    
    for s in results[:k]:
        print(s)

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