题解:P12024 [USACO25OPEN] It's Mooin' Time III B

· · 题解

原来我已经这么老了吗?

首先观察到 q 很小又很大。如果是 \log 询问的话没必要这么小。然后又观察到直接处理几乎不可能,并且字符串只有小写字母。

于是我们可以枚举哞哞叫的起点和终点。花费时间复杂度 O(k^2),其中 k = 26。

假如起点和终点之间的距离为 len,并且你选择的中间点和起点的距离是 a,和终点的距离是 b,那么有 a + b = len 并且你需要让 ab 最大。

我们知道 ab \le \frac{(a+b)^2} 4 当且仅当 a = b 时取得最值。所以我们需要选起点和终点最靠近 \lfloor \frac{a + b} 2 \rfloor 的位置。

我们预处理出来位置 i 左边(包括自己)最近的字符 r 的位置。于是我们可以二分查找出来最靠左的起点和最靠右的终点(容易证明这样一定最优)。然后二分出离 \lfloor \frac{a + b} 2 \rfloor 最近的位置。

时间复杂度 O(kn + qk^2\log n),其中 k = 26。

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int pre[30][N];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, q; cin>>n>>q;
    string str; cin>>str;
    str = " " + str;
    for(int i = 1;i <= n;i++){
        pre[str[i] - 'a' + 1][i] = i;
        for(int j = 1;j <= 26;j++){
            if(pre[j][i] == 0) pre[j][i] = pre[j][i-1];
        }
    }
    while(q--){
        int l, r; cin>>l>>r;
        long long ans = -1;
        for(int i = 1;i <= 26;i++){
            for(int j = 1;j <= 26;j++){
                if(i == j) continue;
                int x = lower_bound(pre[i] + 1, pre[i] + n + 1, l) - pre[i];
                int y = pre[j][r];
                if(x > r || y < l || x > y) continue;
                int mid = (x + y) >> 1;
                int sec = lower_bound(pre[j] + 1, pre[j] + n + 1, mid) - pre[j];
                // if(sec == y) continue;
                int fir = pre[j][sec - 1];
                if(sec != y) ans = max(ans, 1ll * (y - sec) * (sec - x));
                if(fir > x) ans = max(ans, 1ll * (y - fir) * (fir - x));
                // if(ans == 25) cout<<i<<" "<<j<<'\n';
            }
        }
        cout<<ans<<'\n';
    }
    return 0;
}