跳到正文

题解

题解:CF1257C Dominated Subarray

AFO_Lzx约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年4月6日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟
获赞
2
题目
CF1257C

版本

  1. v1当前

题目传送门

Solution\texttt{Solution}

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

Code\texttt{Code}

C++
#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;
}
原文