Problem Description
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.
Input
The first line contains two space-separated integers: n and k (1 ≤ n, k ≤ 105). The second line contains n space-separated integers a1, a2, ..., an — elements of the array a (1 ≤ ai ≤ 105).
Output
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.
Examples
Input |
|
Output |
|
Input |
|
Output |
|
Input |
|
Output |
|
Note
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.
题意:
输入一个长度为n的数组,再输入k,找到一个长度尽量短的区间,使得这个区间里有k个不同的数字。并且这个区间要尽量靠左。
思路:
先从左往右开始遍历,直到找到k个不同的数,确定右端点r,再从右往左遍历,直到找到k个不同的数,再确定左端点l。
代码:
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int a[100001];
bool vis[100001];
int main()
{
int n,k;
int l=0,r=0;
int sum=0;
cin>>n>>k;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
cin>>a[i];
if(vis[a[i]]==0)
{
sum++;
vis[a[i]]=1;
}
}
if(sum<k)
{
cout<<"-1 -1"<<endl;
return 0;
}
sum=0;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
{
if(vis[a[i]]==0)
{
sum++;
vis[a[i]]=1;
if(sum==k)
{
r=i;
break;
}
}
}
sum=0;
memset(vis,0,sizeof(vis));
for(int i=r;i>=1;i--)
{
if(vis[a[i]]==0)
{
sum++;
vis[a[i]]=1;
if(sum==k)
{
l=i;
break;
}
}
}
cout<<l<<" "<<r<<endl;
return 0;
}
break的作用范围:
一个for循环中套用好几个if。 那么一个if中的break作用范围是什么?
然后写了一个测试程序,一个for循环中套用一个if再套用一个if,在最内层的if中加入break,然后运行,程序运行到最内层break的时候就终止了。
所以break的作用是跳出一层循环.<再多的if也都是在一个循环中>