Codeforces - E. Subsegments
E. Subsegments
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in , which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem.
Input
The first line contains two positive integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ n) — the number of array elements and the length of the segment.
Then follow n lines: the i-th one contains a single number ai ( - 109 ≤ ai ≤ 109).
Output
Print n–k + 1 numbers, one per line: on the i-th line print of the maximum number of those numbers from the subarray ai ai + 1 … ai + k - 1 that occur in this subarray exactly 1 time. If there are no such numbers in this subarray, print “Nothing”.
Examples
inputCopy
5 3
1
2
2
3
3
outputCopy
1
3
2
inputCopy
6 4
3
3
3
4
4
2
outputCopy
4
Nothing
3
权值线段树维护最小值即可。
第一步我们可以想到,每次查询时,权值线段树肯定是往右递归最佳,怎么判断右边有等于1的权值呢?
很明显,我们维护最小值即可,但是有一个问题,如果最小值为0,那么怎么判断呢?我们让0 == INF 即可。
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=1e5+10,inf=0x3f3f3f3f;
int n,k,m,a[N],b[N];
struct node{int l,r,mi;}t[N<<2];
inline void push_up(int p){t[p].mi=min(t[p<<1].mi,t[p<<1|1].mi);}
void build(int p,int l,int r){
t[p].l=l; t[p].r=r;
if(l==r) return void(t[p].mi=inf); int mid=l+r>>1;
build(p<<1,l,mid); build(p<<1|1,mid+1,r);
push_up(p);
}
void change(int p,int x,int v){
if(t[p].l==t[p].r){
if(v==1){
if(t[p].mi==inf) t[p].mi=1;
else t[p].mi++;
}else{
if(t[p].mi==1) t[p].mi=inf;
else t[p].mi--;
}
return ;
}
int mid=t[p].l+t[p].r>>1;
if(x<=mid) change(p<<1,x,v);
else change(p<<1|1,x,v);
push_up(p);
}
int ask(int p){
if(t[p].l==t[p].r) return t[p].l;
if(t[p<<1|1].mi==1) return ask(p<<1|1);
else return ask(p<<1);
}
signed main(){
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i],b[i]=a[i];
sort(b+1,b+1+n); m=unique(b+1,b+1+n)-b-1; build(1,1,m);
for(int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+1+m,a[i])-b;
for(int i=1;i<k;i++) change(1,a[i],1);
for(int i=k;i<=n;i++){
change(1,a[i],1);
if(t[1].mi>1) puts("Nothing");
else printf("%d\n",b[ask(1)]);
change(1,a[i-k+1],-1);
}
return 0;
}