codeforces 1257C(map)

2020-10-23 15:19:44 浏览数 (1)

题目描述

Let’s call an array t dominated by value v in the next situation.

At first, array t should have at least 2 elements. Now, let’s calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v)>occ(v′) for any other number v′. 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 a1,a2,…,an. Calculate its shortest dominated subarray or say that there are no such subarrays.

The subarray of a is a contiguous part of the array a, i. e. the array ai,ai 1,…,aj for some 1≤i≤j≤n.

给你n个数字,让你求一个最小的区间,要求区间内有一个多次出现的数字。

思路

使用map记录每次出现的数字,如果出现了一次重复的,就计算一下长度,取min即可。

AC代码

代码语言:javascript复制
#include<bits/stdc  .h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=2*1e5 10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int a[N];
map<int,int> mp;
void solve(){
    mp.clear();
    int n;cin>>n;
    for(int i=1;i<=n;i  ) cin>>a[i];
    int ans=INF;
    for(int i=1;i<=n;i  ){
        if(!mp[a[i]]) mp[a[i]]=i;
        else{
            ans=min(ans,i-mp[a[i]] 1);
            mp[a[i]]=i;
        }
    }
    if(ans==INF) cout<<-1<<endl;
    else cout<<ans<<endl;
}
int main(){
    IOS;
    int t;cin>>t;
    while(t--) solve();
    return 0;
}

0 人点赞