CF1208B

CF1208B

题意:

给出n个数字,找出最小的一端连续区间进行删除操作,使其剩余元素不含重复元素,求要删除的最小区间长度

解法:

删除子段后,前缀和后缀保持不变,可能长度为0.让我们修复不包含任何重复元素的前缀,并找到我们可以获得的最大后缀而不重复元素。 我们可以使用map 来解决问题。

CODE:

#include <iostream> 
#include <cstdio> 
#include <cstring> 
#include <algorithm> 
#include <map> 

using namespace std; 

#define LL long long
#define INF 2147483647
#define N 2010

int a[N],n,ans = INF; 
map<int,int> Hash; 

int main() {
    scanf("%d",&n); 
    for(int i = 1 ; i <= n ; i++)
        scanf("%d",&a[i]); 
    int cnt = n; 
    while(cnt >= 1) {
        if(Hash[a[cnt]] >= 1) break; 
        Hash[a[cnt]]++; 
        cnt--; 
    }
    for (int i = 1; i <= n; i++) {
        ans = min(ans, cnt - i + 1); 
        Hash[a[i]]++; 
        while (Hash[a[i]] >= 2 && cnt <= n) {
            cnt++; 
            Hash[a[cnt]]--; 
        }
        if (Hash[a[i]] >= 2)break; 
    }
    printf("%d\n", ans); 
    system("pause");
    return 0; 
}

猜你喜欢

转载自www.cnblogs.com/Repulser/p/11415082.html
今日推荐