Time Limit:2000MS | Memory Limit:64000KB | 64bit IO Format:%lld & %llu |
Description
Let us consider the sequence a1, a2,..., an of non-negative integer numbers. Denote as ci,j the number of occurrences of the number i among a1,a2,..., aj. We call the sequence k-nice if for all i1<i2 and for all j the following condition is satisfied: ci1,j ≥ ci2,j −k.
Given the sequence a1,a2,..., an and the number k, find its longest prefix that is k-nice.
Input
Output
Sample Input
10 1 0 1 1 0 2 2 1 2 2 3 2 0 1 0
Sample Output
8 0
Source
解析
线段树。其实我只用记录c,c[i]是当前i出现的次数。
每次我读入一个数a进来,c[a]++。只要c[1]...c[a-1]都满足c[i]+K>=c[a]就可以了,一旦不满足就结束程序并输出答案。
那么我找c[1]...c[a-1]中最小的即可。如果最小的都满足不等式就不用验证其他的了。
于是用线段树实现这个查询操作。
注意线段树建树从[0,N]开始,因为The second line contains n integer numbers ranging from 0 to n.
还有我因为tree开小了WA了一发……
#include<cstdio>
#include<fstream>
using namespace std;
int c[200100],N,K,max=0;
struct node
{
int l,r,min;
}tree[200100*4];
void build(int p,int l,int r)
{
tree[p].l=l; tree[p].r=r;
if(l==r) return;
int mid=(l+r)>>1;
build(p<<1,l,mid);
build(p*2+1,mid+1,r);
}
inline int min(int a,int b) {return a<b?a:b;}
void modify(int p,int x)
{
if(tree[p].l==tree[p].r){tree[p].min++;return;}
int mid=(tree[p].l+tree[p].r)>>1;
if(x<=mid)modify(p<<1,x); else modify(p*2+1,x);
tree[p].min=min(tree[p<<1].min,tree[p*2+1].min);
}
int ask(int p,int qr)
{
if(tree[p].r<=qr) return tree[p].min;
int mid=(tree[p].l+tree[p].r)>>1;
int al=ask(p<<1,qr),ar=0x3f3f3f3f;
if(mid<qr) ar=ask(p*2+1,qr);
return min(al,ar);
}
int main()
{
//freopen("nice.in","r",stdin);
//freopen("nice.out","w",stdout);
scanf("%d%d",&N,&K);
build(1,0,N);
int ans=0;
for(int i=1;i<=N;i++)
{
int a;scanf("%d",&a);
c[a]++; modify(1,a);
if(ask(1,a)+K>=c[a]) ans=i;else break;
}
printf("%d",ans);
while(1);
return 0;
}