P14924 [GESP202512 八级] 宝石项链

· · 题解

被八级创飞了……

Analysis

首先通过将数组复制一倍破环为链,即 a_{i+n} \leftarrow a_i(1 \leqslant i \leqslant n),方便处理环跨 1、跨 n。

假设我们已经知道从每个起点 i 开始,最短的包含所有 m 种宝石的段的长度,那么为了最大化段数,我们应该贪心地每次切出该长度,然后从下一个位置开始,因为这时恰好含 m 种。求出这个值可以使用双指针滑动窗口。

求出后可以枚举起点进行贪心,时间复杂度 \Theta(n^2)。

考虑使用倍增优化,定义 st_{k,i} 为从 i 开始连续走 2^k 段的总宝石数。可以分成两个长度为 2^{k-1} 的段,转移为:

st_{k,i} \leftarrow st_{k-1,i} + st_{k-1,(i+st_{k-1,i}-1) \bmod n + 1}

求答案时,枚举起点 i,从高位到低位尝试增加 2^k 段。

AC Code

#include <bits/stdc++.h>
using namespace std;
#define int long long

const int N = 1e5 + 5, LOG = 20, INF = 1e18;

int n, m;
int a[N * 2], st[LOG][N], cnt[N];

int jump(int x){
    int now = 0, sec = 0;
    for(int i = LOG - 1; i >= 0; -- i)
        if(now + st[i][x] <= n){
            now += st[i][x];
            sec += (1 << i);
            x = (x + st[i][x] - 1) % n + 1;
        }
    return sec;
}

signed main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);

    cin >> n >> m;
    for(int i = 1; i <= n; ++ i)
        cin >> a[i], a[i + n] = a[i];

    int r = 0, tot = 0;
    for(int i = 1; i <= n; ++ i){
        while(tot < m && r < 2 * n)
            if(!(cnt[a[++ r]] ++))
                ++ tot;
        st[0][i] = r - i + 1;
        if(!(-- cnt[a[i]]))
            -- tot;
    }

    for(int i = 1; i < LOG; ++ i)
        for(int j = 1; j <= n; ++ j){
            int to = (j + st[i - 1][j] - 1) % n + 1;
            st[i][j] = min(st[i - 1][j] + st[i - 1][to], INF);
        }

    int ans = 0;
    for(int i = 1; i <= n; ++ i)
        ans = max(ans, jump(i));

    cout << ans;

    return 0;
}