重新刷这个经典题,感觉跟以前不一样了,变得更加容易理解了,不讲解了,看代码。注意:要用C++提交,用G++会超时。。
代码:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define N 1000007 int a[N],mp[N],head,tail,n,k; inline void pushup(int i) { while(tail > head && a[i] < a[mp[tail-1]]) tail--; mp[tail++] = i; //mq } inline void pushdown(int i) { while(tail > head && a[i] > a[mp[tail-1]]) tail--; mp[tail++] = i; } void solve(int cmd) { head = tail = 0; int i; void (*push)(int) = cmd?pushdown:pushup; for(i=1;i<=k&&i<=n;i++) push(i); printf("%d",a[mp[head]]); for(;i<=n;i++) { while(head != tail && mp[head] < i-k+1) head++; push(i); printf(" %d",a[mp[head]]); } printf("\n"); } int main() { int i; while(scanf("%d%d",&n,&k)!=EOF) { for(i=1;i<=n;i++) scanf("%d",&a[i]); solve(0); solve(1); } return 0; }