区间最小值求和
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 <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
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(head<tail&&a[q[tail-1]]>a[i]) tail--;
q[tail++]=i;
if(q[head]<i-k+1) head++;
if(i>=k) sum+=a[q[head]];
}
printf("%lld\n",sum);
}
return 0;
}