http://codeforces.com/problemset/problem/224/B
You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 ≤ l ≤ r ≤ n)such, that among numbers al, al + 1, ..., ar there are exactly k distinct numbers.
Segment [l, r] (1 ≤ l ≤ r ≤ n; l, r are integers) of length m = r - l + 1, satisfying the given property, is called minimal by inclusion, if there is no segment [x, y] satisfying the property and less then m in length, such that 1 ≤ l ≤ x ≤ y ≤ r ≤ n. Note that the segment [l, r]doesn't have to be minimal in length among all segments, satisfying the given property.
The first line contains two space-separated integers: n and k (1 ≤ n, k ≤ 105). The second line contains n space-separated integersa1, a2, ..., an — elements of the array a (1 ≤ ai ≤ 105).
Print a space-separated pair of integers l and r (1 ≤ l ≤ r ≤ n) such, that the segment [l, r] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them.
4 2 1 2 2 3
1 2
8 3 1 1 2 2 3 3 4 5
2 5
7 4 4 7 7 4 7 4 7
-1 -1
In the first sample among numbers a1 and a2 there are exactly two distinct numbers.
In the second sample segment [2, 5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments.
In the third sample there is no segment with four distinct numbers.
题目是求一个序列段,包含正好k个不同的数字,这个序列段可以不是最短的,但这序列的任意子段绝对不可能满足含有k个不同的数字。
思路:从第一个数字开始往后,当找到一个数恰好满足k个不同的数时。这个数就是序列的右边界。再来考虑左边界,左边界的数应该满足在这个序列中只出现一次(否则的话,后面还有我们要将它舍去),记录其位置。。。。。。
看代码,注意处理的技巧:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
const int N=300005;
int a[N];
int toal[N];
bool flag[N];
int main()
{
int n,k;
while(~scanf("%d%d",&n,&k))
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
memset(flag,0,sizeof(flag));
memset(toal,0,sizeof(toal));
int sum=0,l,r;
bool val=0;
for(int i=1;i<=n;i++)
{
toal[a[i]]++;//记录每个数字 出现的次数(因为只循环到子段右边界toal就是子段中每个数出现的次数)
if(flag[a[i]])//重复出现不计数
continue;
flag[a[i]]=1;
sum++;
if(sum==k)
{
val=1;
r=i;
break;
}
}
if(val==0)
printf("-1 -1\n");
else
{
for(l=1;l<=r&&toal[a[l]]!=1;l++)//保证第一个数这此子段中出现一次
toal[a[l]]--;
printf("%d %d\n",l,r);
}
}
return 0;
}