CF803D 题解

· · 题解

注意事项

请注意要在输入 n 后空转一次 getline 吃掉换行再输入字符串!

思路

“最大的最小”,一眼二分题。

先把原字符串按减号和空格拆了,然后只要二分答案,贪心取走每个子段,若当前总和超限了那就新开一段,最后只要看段数有没有到 n 就行辣。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int n, m, a[1000005], tot = 0, l = 1, r, mid, best;
string s;
bool check () {
    int tot = 0, sum = 0;
    for (int i = 0; i <= m; ++ i)
        if ((sum += a[i]) > mid)
            if (++ tot > n)
                return 0;
            else
                -- i, sum = 0;
    return tot < n;
}
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> n;
    getline (cin, s);
    getline (cin, s);
    for (char& i : s)
        if (i == '-' || i == ' ')
            a[m] = tot + 1, ++ m, tot = 0;
        else
            ++ tot;
    a[m] = tot;
    r = s.size ();
    while (l <= r) {
        mid = l + r >> 1;
        if (check ())
            r = mid - 1, best = mid;
        else
            l = mid + 1;
    }
    cout << best;
    return 0;
}