CF1257C Dominated Subarray

题意简述:

给定一个序列 找出其中最短的连续子段使得子段中只有一个众数(子段长度大于等于2)

题解:

首先考虑一下假如有一段连续相同的数字 那么答案就一定是2 即从连续的一段中随便挑连续的两个 那么众数就是这个数 那么接下来只剩下没有连续相同数字的情况

那么我们可以考虑一下答案是怎么构成的 因为是最短 所以肯定是首位两个的数字相同 中间是其他的数字 那么我们就可以扫一遍数组 每次对于数字相同的相邻的两个位置做差取最小值 那么就肯定可以得到答案了

AC代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
template<class T>inline void read(T &x) {
    x=0; int ch=getchar(),f=0;
    while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    if(f)x=-x;
}
const int inf=0x3f3f3f3f;
const int maxn=200050;
int T,n;
int a[maxn];
int last[maxn];
int main()
{
	cin>>T;
	while(T--)
	{
		
		read(n);
		for(int i=1;i<=n;i++) read(a[i]);
		for(int i=0;i<=n;i++) last[i]=0;
		if(n==1) puts("-1");
		else
		{
			int ans=inf;
			for(int i=1;i<=n;i++)
			{
				if(last[a[i]]!=0)
				{
					ans=min(ans,i-last[a[i]]+1);
				}
				last[a[i]]=i;
			}
			if(ans==inf) puts("-1");
			else cout<<ans<<endl;
		}
	}
	return 0;
}