D. Longest k-Good Segment

120 阅读1分钟

题目

The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.

Find any longest k-good segment.

As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

输入

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k.

The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

输出

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

解法

我们通过set来维护当前[l, r]区间重不同数字的个数如果当前的个数超过了m那么我们就从左往右删除直到删除一个个数只有一个的数字

Code

#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <cmath>
#include <set>
#include <stack>
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int long long
#define endl '\n'
#define pb push_back
#define NO cout << "NO" << endl;
#define YES cout << "YES" << endl;
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
#define rep(i,a,n) for (int i=a;i<=n;i++)
#define per(i,a,n) for (int i=n;i>=a;i--)
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<VI> VII;
ll MOD = 998244353;
ll powmod(ll a,ll b) {ll res=1;a%=MOD; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
mt19937 mrand(random_device{}()); 
const int N = 1e6 + 10;
int st[N][21], lg[N];
int a[N], n;
ll mp[N];
void solve()
{
    PII res;
    ll mx = 0;
    
    int  m; scanf("%lld %lld", &n, &m);
    rep (i, 1, n) scanf("%lld", a + i);
    set<int> st;
    int l = 1;
    for (int i = 1; i <= n; i++) {
        st.insert(a[i]);
        mp[a[i]] ++;
        while (st.size() > m) {
            while(mp[a[l]] > 1) {
                mp[a[l]]--;
                l ++;
            } 
            mp[a[l]]--;
            st.erase(a[l]);
            l++;
        }
        if (i - l + 1 > mx) {
            mx = i - l + 1;
            res = {l, i};
        }
    }
    printf("%lld %lld", res.fi, res.se);
}
signed main()
{
    // ios::sync_with_stdio(false);
    // cin.tie(0); cout.tie(0);
    // int T;cin >> T;
    // while ( T -- )
    solve();
    return 0;
}