To solve this problem you have to do a "move" subsegment and know :
1. The set B of numbers, meeting once, with the function of extracting the maximum for O (logN)
2.The set of numbers appearing on this subsegments with keeping the number of times,that this number is found on this subsegments, with function of verifying how many times the number in this subsegments for O (logN).
While moving a segment from (a[i] .. a[i + k - 1]) for 1 item left (a[I + 1] .. a[I + k]) you have to:
1) Check whether a[i] with a[I + k]. If yes, then there is no need to modify the set, otherwise proceed to item 2 and 3.
2) Check how many times we have a[i] in the set A: if 2, then add a[i] to B, if 1, then remove it from A and B. Do not forget to reduce the corresponding number of occurrences of a[i] in the current segment 1.
3) Check, how many times we have a[I + k] in the set A: if 0, then add a[i] in the B and A, if 1, then remove it from B. Do not forget to increase the corresponding number of occurrences of a[i] the current interval to 1.
After that, if the set is not empty, we should take peak from it.
So the asymptotics of this process will be O(NlogN).
As such data structures set / map(for those who use C + +) and the Cartesian tree are suitable.
----------------------------------------写的有点挫。。。
#include <iostream> #include <map> using namespace std; map<int,int>mp; map<int,int>::iterator it; map<int,int>co; int n,k; int a[111111]; int main() { cin>>n>>k; for (int i=1; i<=n; i++) cin>>a[i]; for (int i=1; i<=k; i++) { mp[a[i]]++; if (mp[a[i]]==1) { co.insert(pair<int,int>(a[i],1)); } else { if (co.find(a[i])!=co.end()) co.erase(a[i]); } } it=co.end(); if (it!=co.begin()) it--; if (co.empty()) cout<<"Nothing"<<endl; else cout<<it->first<<endl; for (int i=k+1; i<=n; i++) { mp[a[i]]++; mp[a[i-k]]--; if (mp[a[i]]==1) { co.insert(pair<int,int>(a[i],1)); } else { if (co.find(a[i])!=co.end()) co.erase(a[i]); } if (mp[a[i-k]]==1) { co.insert(pair<int,int>(a[i-k],1)); } else { if (co.find(a[i-k])!=co.end()) co.erase(a[i-k]); } it=co.end(); if (it!=co.begin()) it--; if (co.empty()) cout<<"Nothing"<<endl; else cout<<it->first<<endl; } return 0; }