1. 程式人生 > 其它 >Jessica's Reading Problem

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;
}