被八级创飞了……
Analysis
首先通过将数组复制一倍破环为链,即 (),方便处理环跨 、跨 。
假设我们已经知道从每个起点 开始,最短的包含所有 种宝石的段的长度,那么为了最大化段数,我们应该贪心地每次切出该长度,然后从下一个位置开始,因为这时恰好含 种。求出这个值可以使用双指针滑动窗口。
求出后可以枚举起点进行贪心,时间复杂度 。
考虑使用倍增优化,定义 为从 开始连续走 段的总宝石数。可以分成两个长度为 的段,转移为:
求答案时,枚举起点 ,从高位到低位尝试增加 段。
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;
}