b467簡單

最佳一列

運用逐列加總並保留最早最大值,正確求解本題並處理邊界情況。

解題思路

逐列計算元素和,再與目前最佳列比較。

只在新和嚴格更大時更新列號;相同時保留既有較早列。因此掃描後得到最大和、並列時最小編號。

時間 O(RC),Python 讀取 O(RC),C++ 額外 O(1)。

Step-by-step animation

教學例子:三列和分別為-3、5、5。

回報動畫錯誤
步驟 1 / 3

步驟 1

三列和分別為-3、5、5。

-3
5
5
狀態
最佳尚未定

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    long long best = LLONG_MIN;
    int pos = 0;
    for (int i = 1; i <= R; i++) {
        long long s = 0, x;
        for (int j = 0; j < C; j++) {
            cin >> x;
            s += x;
        }
        if (s > best) {
            best = s;
            pos = i;
        }
    }
    cout << pos << ' ' << best << '\n';
}

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

更多