Educational Codeforces Round 76 (Rated for Div. 2) C. Dominated Subarray 水题

試著忘記壹切 提交于 2019-12-04 11:40:45

C. Dominated Subarray

Let's call an array 𝑡 dominated by value 𝑣 in the next situation.

At first, array 𝑡 should have at least 2 elements. Now, let's calculate number of occurrences of each number 𝑛𝑢𝑚 in 𝑡 and define it as 𝑜𝑐𝑐(𝑛𝑢𝑚). Then 𝑡 is dominated (by 𝑣) if (and only if) 𝑜𝑐𝑐(𝑣)>𝑜𝑐𝑐(𝑣′) for any other number 𝑣′. For example, arrays [1,2,3,4,5,2], [11,11] and [3,2,3,2,3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1,2] and [3,3,2,2,1] are not.

Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.

You are given array 𝑎1,𝑎2,…,𝑎𝑛. Calculate its shortest dominated subarray or say that there are no such subarrays.

The subarray of 𝑎 is a contiguous part of the array 𝑎, i. e. the array 𝑎𝑖,𝑎𝑖+1,…,𝑎𝑗 for some 1≤𝑖≤𝑗≤𝑛.

Input

The first line contains single integer 𝑇 (1≤𝑇≤1000) — the number of test cases. Each test case consists of two lines.

The first line contains single integer 𝑛 (1≤𝑛≤2⋅105) — the length of the array 𝑎.

The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤𝑛) — the corresponding values of the array 𝑎.

It's guaranteed that the total length of all arrays in one test doesn't exceed 2⋅105.

Output

Print 𝑇 integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or −1 if there are no such subarrays.

Example

input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
output
-1
6
3
2

Note

In the first test case, there are no subarrays of length at least 2, so the answer is −1.

In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray.

In the third test case, the subarray 𝑎4,𝑎5,𝑎6 is the shortest dominated subarray.

In the fourth test case, all subarrays of length more than one are dominated.

题意

现在定义一个Dominated number,表示这个序列中这个数字出现最多。

现在给n个数,你需要找到一个最短的区间,使得这个区间里面存在唯一一个出现次数最多的数。

题解

其实思考思考,我们会发现出现最多的就是出现两个而已。

那么我们就暴力枚举每一个数,看上一个数在哪个位置即可,然后选择最短的就行。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 200005;
int n,a[maxn],c[maxn];
void solve(){
    cin>>n;
    int mx = 9999999;
    for(int i=1;i<=n;i++){
        c[i]=0;
    }
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if(c[a[i]]!=0){
            mx=min(i-c[a[i]]+1,mx);
        }
        c[a[i]]=i;
    }
    if(mx==9999999){
        cout<<"-1"<<endl;
    }else{
        cout<<mx<<endl;
    }
}
int main(){
    int t;cin>>t;
    while(t--)solve();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!