http://poj.org/problem?id=3320
为了避免开一个下标范围过大的数组,可以用set统计不同的数的个数,用map记录某一个数的一些信息。
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#define N 1000005
using namespace std;
int a[N];
int main()
{
int n, cnt, s, t, sum, res;
scanf("%d", &n);
set <int> all;
cnt = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
all.insert(a[i]);
}
s = 0, t = 0, sum = 0;
res = n;
cnt = all.size();
map <int, int> Count;
for (;;)
{
while (t < n && sum < cnt)
{
if (Count[a[t]] == 0)
{
Count[a[t]] = 1;
sum++;
}
else Count[a[t]]++;
t++;
}
if (sum < cnt) break;
res = min(res, t - s);
if (Count[a[s]] == 1)
{
Count[a[s]] = 0;
sum--;
}
else Count[a[s]]--;
s++;
}
printf("%d\n", res);
return 0;
}