a191簡單字串、字元與格式解析

TOI 2020/10 新手組:分組

將 P 當字串,由右至左每 N 位計算一組總和。

前往題目練習 →回報教學錯誤位數 L:時間 O(L),空間 O(L)。

這題在學什麼

最右 N 位是第 1 組,之後每次向左移動 N 位;最左不足 N 位仍成一組。

每組將字元轉成數字後相加,不是把整組當成一個整數比較。

由小組號往大組號處理,總和大於等於目前最佳時更新,便能讓同分選最大組號。

Step-by-step animation

分組・從右分段及同分選大編號

回報動畫錯誤
步驟 1 / 3

最右一組

72140588 的末三位是 588。

72
140
588
組別
1
總戰力
21

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    string p;
    cin >> n >> p;
    int group = 0, best = -1, who = 0;
    for (int end = (int)p.size(); end > 0; end -= n) {
        ++group;
        int sum = 0;
        for (int i = max(0, end - n); i < end; i++)
            sum += p[i] - '0';
        if (sum >= best) {
            best = sum;
            who = group;
        }
    }
    cout << who << ' ' << best << '\n';
}

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

更多