codeforces 1257C(map)

題目描述

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代碼

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章