比赛 Segment Tree Competition 评测结果 AAAAAAAAA
题目名称 滑动窗口 最终得分 100
用户昵称 _Itachi 运行时间 1.335 s
代码语言 C++ 内存使用 2.75 MiB
提交时间 2016-08-28 19:03:21
显示代码纯文本
  1. #include<cstdio>
  2. #include<string>
  3. #include<cstring>
  4. #include<deque>
  5. #include<iostream>
  6. #define maxn 1000005
  7. using namespace std;
  8. int a[maxn];
  9. int main(){
  10. freopen("window.in","r",stdin);
  11. freopen("window.out","w",stdout);
  12. int k,n,x,y,f,b;
  13. deque<int>h,l;
  14. scanf("%d%d",&n,&k);
  15. if(k>n)k=n;//鲁棒性,如果区间比数量大,把数量赋值给区间
  16. for(int i=1;i<=n;i++)
  17. scanf("%d",&a[i]);
  18. h.push_front(1);
  19. l.push_front(1);//把第一个进去 ,因为只有一个,必是最大和最小
  20. for(int i=2;i<=k;i++){
  21. while(y=h.back(),a[y]<=a[i]){
  22. h.pop_back();
  23. if(h.empty())break;
  24. }//因为1一开始入队 ,所以一定非空
  25. //将队尾比自己小或相等的去掉(以为自己后过期,当自己过期时 ,一定删掉的早已过期,无法继承)
  26. h.push_back(i);//将自己进去,因为自己可能继承
  27. while(x=l.back(),a[x]>=a[i]){
  28. l.pop_back();
  29. if(l.empty())break;
  30. }//因为1一开始入队 ,所以一定非空
  31. //将队尾比自己大的或相等的去掉(以为自己后过期,当自己过期时 ,一定删掉的早已过期,无法继承)
  32. l.push_back(i);//将自己进去,因为自己可能继承
  33. }//把前k个压进去
  34. printf("%d ",a[l.front()]);//输出第一个区间最小值
  35. for(int i=k+1;i<=n;i++){
  36. b=l.front();//检查队首是否过期
  37. if(b==i-k)l.pop_front();//因为队后的一定比队首晚入,所以只需判断队首
  38. if(l.empty())l.push_front(i);//如果队空了,直接压进去
  39. else {
  40. while(x=l.back(),a[x]>=a[i]){
  41. l.pop_back();
  42. if(l.empty())break;
  43. }//将队尾比自己大的或相等的去掉(以为自己后过期,当自己过期时 ,一定删掉的早已过期,无法继承)
  44. l.push_back(i);//把自己加进去
  45. }
  46. printf("%d ",a[l.front()]);//输出区间最小值
  47. }//处理最小值
  48. printf("\n%d ",a[h.front()]);//输出第一个区间最大值
  49. for(int i=k+1;i<=n;i++){
  50. f=h.front();//检查队首是否过期
  51. if(f==i-k)h.pop_front();//因为队后的一定比队首晚入,所以只需判断队首
  52. if(h.empty())h.push_front(i);//如果队空了,直接压进去
  53. else {
  54. while(y=h.back(),a[y]<=a[i]){
  55. h.pop_back();
  56. if(h.empty())break;
  57. }//将队尾比自己小或相等的去掉(以为自己后过期,当自己过期时 ,一定删掉的早已过期,无法继承)
  58. h.push_back(i);//把自己加进去
  59. }
  60. printf("%d ",a[h.front()]);//输出区间最大值
  61. }//处理最大值
  62. }