From e97574f3e5632968b49ad61c6c344fe828bc403e Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Tue, 16 Jul 2024 08:17:50 +0800 Subject: [PATCH] =?UTF-8?q?P1638=20=E9=80=9B=E7=94=BB=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/166266843 --- Luogu/P1638/P1638.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Luogu/P1638/P1638.cpp diff --git a/Luogu/P1638/P1638.cpp b/Luogu/P1638/P1638.cpp new file mode 100644 index 00000000..40fc0c76 --- /dev/null +++ b/Luogu/P1638/P1638.cpp @@ -0,0 +1,61 @@ +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1e6 + 5, + M = 2e3 + 5; + +int n, m, a[N]; +int cnt, b[M]; // 记录出现过的数 +int ans, ans_l, ans_r; + +void insert(int x) { + if (b[x] == 0) cnt++; // 维护数的数目 + b[x]++; // 维护数的出现次数 +} + +void erase(int x) { + b[x]--; // 维护数的出现次数 + if (b[x] == 0) cnt--; // 维护数的数目 +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> m; + + for (int i = 1; i <= n; i++) { + cin >> a[i]; + } + + ans = std::numeric_limits::max(); + + for (int i = 1, j = 1; i <= n; i++) { + insert(a[i]); // 先维护右指针 + + while (true) { + erase(a[j]); + + if (cnt == m) { // 删了以后还是满足条件 + j++; // 维护左指针 + } else { + insert(a[j]); // 恢复 + break; + } + } + + if (cnt == m && i - j + 1 < ans) { // 记录答案 + ans = i - j + 1; + ans_l = j; + ans_r = i; + } + } + + cout << ans_l << ' ' << ans_r << endl; + + return 0; +}