题解:CF1257C Dominated Subarray

· · 题解

题目传送门

\texttt{Solution}

简单的贪心。如果一个子数组被支配了,那么就是只有一个唯一的众数,现在需要求出这个子数组的最短长度,那么所有可能的情况就应该是有 1 个数字在这个子数组中出现了 2 次,这个子数组中其它的数字都只出现 1 次。所以我们用 map 记录一个数字 x 上一次出现的下标为 last_x,等这个数字 x 再一次出现在下标 i 时就用 i-last_x+1 更新答案。最终如果无解输出 -1 即可。

\texttt{Code}

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

unordered_map<int, int> last;
int T, n, x;

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    cin >> T;

    while (T--) {
        cin >> n;
        last.clear();
        int ans = INT_MAX;
        for (int i = 1; i <= n; i++) {
            cin >> x;
            if (last[x]) ans = min(ans, i - last[x] + 1);
            last[x] = i;
        }
        if (ans == INT_MAX) cout << -1 << '\n';
        else cout << ans << '\n';
    }
    return 0;
}