Jessica's Reading Problem
Jessica's Reading Problem
SCUACM2022集训前训练-数据结构 - Virtual Judge (vjudge.net)
双指针
假设当前枚举的区间是 \([l,r]\), 且是以 \(r\) 为右端点的最大的可以满足条件的 \(l\), 那么 \(r++\) 时这个 \(l\) 肯定还能满足条件,所以 \(l\) 不会回退,可以用双指针
用 map 记录当前区间是否能覆盖所有知识点 (now.size() == m), 当某一个知识点的次数为 0 时,在 map 里删去
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;
int n;
int a[N];
int main()
{
scanf("%d\n", &n);
map<int, int> alls;
for (int i = 1; i <= n; i++)
{
scanf("%d", a + i);
alls[a[i]]++;
}
int m = alls.size();
int ans = n;
map<int, int> now;
for (int l = 1, r = 1; r <= n; r++)
{
now[a[r]]++;
while(l <= r && now.size() == m)
{
ans = min(ans, r - l + 1);
now[a[l]]--;
if (now[a[l]] == 0)
now.erase(a[l]);
l++;
}
}
printf("%d\n", ans);
return 0;
}