b335中等

93 臺北市資訊學科能力競賽(2004)|最大子矩陣

依精確生成規則求非空最大子矩陣總和。

解題思路

依精確生成規則求非空最大子矩陣總和。

先建N×N矩陣,第一格保留s,第i列首格i≥2為s+i;後續格依前值×17的朝零餘數及(−1)^(i+j)生成。

枚舉上、下界列,把這個列帶各欄和壓成一維陣列;在其上跑非空Kadane最大連續區間和。

每個矩形都有唯一上下列界及左右連續區間,因此枚舉所有列帶並取最大必涵蓋最優矩形。

每筆時間 O(N³)次大整數加比,工作空間 O(N²)個大整數。Python一次split另保留全部種子與尺寸;所有數值位數成本另計。

Step-by-step animation

N=2、種子s=1的完整生成示例

回報動畫錯誤
步驟 1 / 3

步驟 1

示例N=2,s=1,首欄為1、3。

1 ?
3 ?
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
    int n;
    cpp_int s;
    while (cin >> n >> s) {
        vector<vector<cpp_int>> a(n, vector<cpp_int>(n));
        for (int i = 0; i < n; i++) {
            a[i][0] = i ? s + i + 1 : s;
            for (int j = 1; j < n; j++) {
                a[i][j] = (a[i][j - 1] * 17) % 103;
                if ((i + j) % 2)
                    a[i][j] = -a[i][j];
            }
        }
        cpp_int best = a[0][0];
        for (int top = 0; top < n; top++) {
            vector<cpp_int> v(n);
            for (int bot = top; bot < n; bot++) {
                cpp_int end = 0;
                for (int j = 0; j < n; j++) {
                    v[j] += a[bot][j];
                    if (j == 0)
                        end = v[j];
                    else {
                        cpp_int ext = end + v[j];
                        end = ext > v[j] ? ext : v[j];
                    }
                    if (end > best)
                        best = end;
                }
            }
        }
        cout << best << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多