[关闭]
@Chilling 2017-02-16T17:57:49.000000Z 字数 2054 阅读 1356

POJ-2823: Sliding Window(区间最值)

线段树


链接:POJ-2823

Description

An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example:
The array is [1 3 -1 -3 5 3 6 7], and k is 3.

Window position Minimum value Maximum value
[1 3 -1] -3 5 3 6 7 -1 3
1 [3 -1 -3] 5 3 6 7 -3 3
1 3 [-1 -3 5] 3 6 7 -3 5
1 3 -1 [-3 5 3] 6 7 -3 5
1 3 -1 -3 [5 3 6] 7 3 6
1 3 -1 -3 5 [3 6 7] 3 7

Your task is to determine the maximum and minimum values in the sliding window at each position.

Input

The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.

Output

There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.

Sample Input

8 3
1 3 -1 -3 5 3 6 7

Sample Output

-1 -3 -3 -3 3 3
3 3 5 5 6 7

题意:给出n个数,求连续的k个数字中的最大值和最小值。区间内最大值和最小值的查询,n比较大,超过了,用RMQ做的话超内存了…


  1. #include<stdio.h>
  2. #include<algorithm>
  3. using namespace std;
  4. int a[1000005];
  5. struct node
  6. {
  7. int l,r,maxs,mins;
  8. }s[4*1000005];
  9. void build(int id,int l,int r)
  10. {
  11. s[id].l=l;
  12. s[id].r=r;
  13. if(l==r)
  14. s[id].maxs=s[id].mins=a[l];
  15. else
  16. {
  17. int mid=(l+r)/2;
  18. build(id*2,l,mid);
  19. build(id*2+1,mid+1,r);
  20. s[id].maxs=max(s[id*2].maxs,s[id*2+1].maxs);
  21. s[id].mins=min(s[id*2].mins,s[id*2+1].mins);
  22. }
  23. }
  24. int big(int id,int l,int r)
  25. {
  26. if(l<=s[id].l&&s[id].r<=r)
  27. return s[id].maxs;
  28. int mid=(s[id].l+s[id].r)/2;
  29. if(r<=mid)
  30. return big(id*2,l,r);
  31. else if(l>mid)
  32. return big(id*2+1,l,r);
  33. else
  34. return max(big(id*2,l,r),big(id*2+1,l,r));
  35. }
  36. int small(int id,int l,int r)
  37. {
  38. if(l<=s[id].l&&s[id].r<=r)
  39. return s[id].mins;
  40. int mid=(s[id].l+s[id].r)/2;
  41. if(r<=mid)
  42. return small(id*2,l,r);
  43. else if(l>mid)
  44. return small(id*2+1,l,r);
  45. else
  46. return min(small(id*2,l,r),small(id*2+1,l,r));
  47. }
  48. int main()
  49. {
  50. int n,k;
  51. while(scanf("%d%d",&n,&k)!=EOF)
  52. {
  53. for(int i=1;i<=n;i++)
  54. scanf("%d",&a[i]);
  55. build(1,1,n);
  56. for(int st=1;st<=n-k+1;st++)
  57. {
  58. int en=st+k-1;
  59. if(st==1)
  60. printf("%d",small(1,st,en));
  61. else
  62. printf(" %d",small(1,st,en));
  63. }
  64. printf("\n");
  65. for(int st=1;st<=n-k+1;st++)
  66. {
  67. int en=st+k-1;
  68. if(st==1)
  69. printf("%d",big(1,st,en));
  70. else
  71. printf(" %d",big(1,st,en));
  72. }
  73. printf("\n");
  74. }
  75. return 0;
  76. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注