nefu 1268 区间最小值求和(单调队列)

区间最小值求和 Problem:1268 Time Limit:2000ms Memory Limit:65535K Descrip

区间最小值求和

Problem:1268
Time Limit:2000ms
Memory Limit:65535K

Description

有一个包含n个正整数的数列a[1]~a[n],求数列中所有长度为k的区间的最小值的和?

Input

输入包含多组数据。每组数据第一行为n和k(1<=n<=1e6,1<=k<=n),第二行为n个正整数a[i](0<=a[i]<=1e9)。

Output

输出所有长度为k的区间的最小值的和。

Sample Input

9 5
3 21 5 6 23 5 2 5 7
10 4
1 2 3 5 5 3 6 3 21 3

Sample Output

14
18

中文题。

思路:单调队列

当时用RMQ写超内存了。后来学习了单调队列的写法,就能过。

#include 
#include 
#include 
#include 
using namespace std;
const int maxn=1e6+5;
int q[maxn],a[maxn];
int main()
{int n,k;while(~scanf("%d%d",&n,&k)){int head=1,tail=1;long long sum=0;for(int i=1;i<=n;i++){scanf("%d",&a[i]);while(heada[i]) tail--;q[tail++]=i;if(q[head]=k) sum+=a[q[head]];}printf("%lld\n",sum);}return 0;
}