結果

問題 No.755 Zero-Sum Rectangle
ユーザー lam6er
提出日時 2025-03-20 20:26:49
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 371 ms / 2,000 ms
コード長 2,018 bytes
コンパイル時間 148 ms
コンパイル使用メモリ 82,188 KB
実行使用メモリ 78,788 KB
最終ジャッジ日時 2025-03-20 20:28:02
合計ジャッジ時間 7,575 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 11 TLE * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import defaultdict

def main():
    input = sys.stdin.read().split()
    ptr = 0
    N = int(input[ptr])
    ptr +=1
    M = int(input[ptr])
    ptr +=1

    A = []
    for _ in range(M):
        row = list(map(int, input[ptr:ptr+M]))
        ptr += M
        A.append(row)
    
    # Precompute prefix_row: prefix_row[i][j] is sum of first i rows in column j (1-based)
    prefix_row = [[0]*(M+1) for _ in range(M+1)]
    for i in range(1, M+1):
        for j in range(1, M+1):
            prefix_row[i][j] = prefix_row[i-1][j] + A[i-1][j-1]
    
    queries = []
    for _ in range(N):
        x = int(input[ptr])
        ptr +=1
        y = int(input[ptr])
        ptr +=1
        queries.append((x, y))
    
    for x, y in queries:
        total = 0
        # Iterate all a from 1 to x, c from x to M
        for a in range(1, x+1):
            for c in range(x, M+1):
                # Compute S for this a and c
                S = []
                for j in range(1, M+1):
                    s = prefix_row[c][j] - prefix_row[a-1][j]
                    S.append(s)
                # Compute prefix sums for S
                P = [0]
                for num in S:
                    P.append(P[-1] + num)
                # Process y_code: original y is 1-based, convert to 0-based in S (y_code = y-1)
                y_code = y -1
                # Build frequency map for P[b_code] where b_code ranges from 0 to y_code (inclusive)
                freq = defaultdict(int)
                for b_code in range(0, y_code +1):
                    current_p = P[b_code]
                    freq[current_p] += 1
                # Check d_code from y_code to M-1 (0-based indices in S)
                current = 0
                for d_code in range(y_code, len(S)):
                    # val is P[d_code+1]
                    val = P[d_code+1]
                    current += freq.get(val, 0)
                total += current
        print(total)

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