結果
| 問題 |
No.1345 Beautiful BINGO
|
| コンテスト | |
| ユーザー |
gew1fw
|
| 提出日時 | 2025-06-12 16:05:35 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,524 bytes |
| コンパイル時間 | 205 ms |
| コンパイル使用メモリ | 82,376 KB |
| 実行使用メモリ | 76,256 KB |
| 最終ジャッジ日時 | 2025-06-12 16:05:43 |
| 合計ジャッジ時間 | 6,819 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 23 TLE * 1 -- * 37 |
ソースコード
import sys
from itertools import combinations
def main():
N, M = map(int, sys.stdin.readline().split())
grid = []
for _ in range(N):
row = list(map(int, sys.stdin.readline().split()))
grid.append(row)
# 定义每个格子的坐标,并为每个格子分配一个唯一的位
# (i,j) --> i*N + j
def get_pos(i, j):
return i * N + j
lines = []
# 添加行
for i in range(N):
line = []
total = 0
for j in range(N):
pos = get_pos(i, j)
line.append(pos)
total += grid[i][j]
lines.append((total, line))
# 添加列
for j in range(N):
line = []
total = 0
for i in range(N):
pos = get_pos(i, j)
line.append(pos)
total += grid[i][j]
lines.append((total, line))
# 添加主对角线
line = []
total = 0
for i in range(N):
j = i
pos = get_pos(i, j)
line.append(pos)
total += grid[i][j]
lines.append((total, line))
# 添加副对角线
line = []
total = 0
for i in range(N):
j = N - 1 - i
pos = get_pos(i, j)
line.append(pos)
total += grid[i][j]
lines.append((total, line))
# 预计算每条线的mask
masks = []
for line in lines:
mask = 0
for pos in line[1]:
mask |= (1 << pos)
masks.append((line[0], mask))
# 构建每个位置的值
pos_values = {}
for i in range(N):
for j in range(N):
pos = get_pos(i, j)
pos_values[pos] = grid[i][j]
# 按mask的总和排序
masks.sort(key=lambda x: x[0])
min_total = float('inf')
total_lines = len(masks)
# 尝试选k条线,k从M到total_lines
for k in range(M, total_lines + 1):
# 生成所有k条线的组合
for combo in combinations(masks, k):
# 计算这些线的并集的总和
combined_mask = 0
for m in combo:
combined_mask |= m[1]
# 计算总和
current_sum = 0
for pos in range(N*N):
if (combined_mask >> pos) & 1:
current_sum += pos_values[pos]
if current_sum < min_total:
min_total = current_sum
# 提前终止,如果已经找到更优解
if min_total == 0:
break
print(min_total)
if __name__ == '__main__':
main()
gew1fw