C.Dominated Subarray

Title: subsequence dominated by

Meaning of the questions: t sequence has at least two elements, we call digital sequence t appears to be the largest number of elements v dominant, and the largest number of elements that appear to be unique

You have been given a sequence a1, a2, ..., an, which is calculated by the shortest leading sequence, or that there is no such sequence
[4, 1, 2, 4, 5, 4, 3, 2, 1] the shortest sequence is dominated by [4, 5, 4]
link :( sequences dominated by) [ https://codeforces.com/contest/1257/problem/C ]

Analysis: We can check each the same number (dominated by element) to the distance between them is obtained, and then taken up in the minimum distance from each pair
but may have a better method, time complexity is O (n ) , we can start from scratch check element, if the same element is present, it calculated the distance between them, then the back of the element as the next paragraph start by the beginning of the dominant sequence.

Proof: each segment dominated by pairwise sequence clear, and there is not the same at both ends of the elements, or a shorter dominant sequence will be generated by

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
 
using namespace std;
 
const int N = 2e5 + 5;
const int INF = 0x3f3f3f3f;
vector<int> a;
void solve()
{
    int n;
    cin >> n;
    a.resize(n + 1);
 
    for (int i = 0; i < n; ++i)
        cin >> a[i];
    if (n == 1)
    {
        cout << -1 << endl;
        return;
    }
    int ans = INF;
    vector<int> lst(n + 1, -1);//n + 1个 -1
 
    for (int i = 0; i < n; i++) {
        if (lst[a[i]] != -1)
            ans = min(ans, i - lst[a[i]] + 1);
        lst[a[i]] = i;
    }
    if (ans > n)
        ans = -1;
    cout << ans << endl;
    a.clear();
    lst.clear();
}
 
 
int main()
{
    int T;
    cin >> T;
    for (int i = 1; i <= T; ++i)
    {
        solve();
    }
 
    return 0;
}

Guess you like

Origin www.cnblogs.com/pixel-Teee/p/11962038.html