[CF] B. Variety is Discouraged - Codeforces Round 1005 (Div. 2)
Solutions Codeforces 贪心 双指针 Easy
Lastmod: 2025-02-18 周二 23:15:56

https://codeforces.com/contest/2064/problem/B

题目大意

给出 $n$ 长的不含 $0$ 的数组 $a$。定义一个数组的权值为其长度减去不重复元素个数。

可以最多删除数组中连续的一个非空子段。问怎样删可以使得权值最大。不删最好时返回 $0$,否则返回删除的区间端点。多个可行删法时删掉使结果数组长度尽量小,仍有多种删法时输出任意删法。

$1 \le n \le 2 \times 10^5$。$1 \le a_i \le n$。

简要题解

注意到只有删频率为 $1$ 的数可以使结果不变,否则将会使结果变小,因此如果没有频率为 $1$ 的元素则输出 $0$。其他时候找一个最长的全部频率为 $1$ 的子段即可。

复杂度

$T$:$O()$

$S$:$O()$

代码实现

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

int io_=[](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();

using LL = long long;
using ULL = unsigned long long;
using LD = long double;
using PII = pair<int, int>;
using VI = vector<int>;
using MII = map<int, int>;

template<typename T> void cmin(T &x,const T &y) { if(y<x) x=y; }
template<typename T> void cmax(T &x,const T &y) { if(x<y) x=y; }
template<typename T> bool ckmin(T &x,const T &y) { 
    return y<x ? (x=y, true) : false; }
template<typename T> bool ckmax(T &x,const T &y) { 
    return x<y ? (x=y, true) : false; }
template<typename T> void cmin(T &x,T &y,const T &z) {// x<=y<=z 
    if(z<x) { y=x; x=z; } else if(z<y) y=z; }
template<typename T> void cmax(T &x,T &y,const T &z) {// x>=y>=z
    if(x<z) { y=x; x=z; } else if(y<z) y=z; }

// mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
// mt19937_64 rnd_64(chrono::system_clock::now().time_since_epoch().count());

/*
---------1---------2---------3---------4---------5---------6---------7---------
1234567890123456789012345678901234567890123456789012345678901234567890123456789
*/

void solve() {
  int n; cin >> n;
  vector<int> a(n);
  for (int& i : a) cin >> i;

  vector<int> cnt(n + 1);
  for (int i : a) cnt[i]++;

  int l = 0, r = -1;

  for (int i = 0; i < n; ) {
    if (cnt[a[i]] > 1) {
      i++;
      continue;
    }

    int j = i;
    while (j < n && cnt[a[j]] == 1) {
      j++;
    }

    if (j - i > r - l + 1) {
      l = i;
      r = j - 1;
    }

    i = j;
  }

  if (r == -1) {
    cout << "0\n";
  } else {
    cout << (l + 1) << ' ' << (r + 1) << '\n';
  }
}

int main() {
  int t = 1; 
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
Prev: [CF] C. Remove the Ends - Codeforces Round 1005 (Div. 2)
Next: [CF] B. Segment Occurrences - Educational Codeforces Round 48 (Rated for Div. 2)