HDU - 3415 Max Sum of Max-K-sub-sequence

题意:求长度不超过K的最大的连续序列的和

思路:采用单调队列,我们要求的是Max{sum[i]-sum[j]}(i-j<=k),可以这么想每次的i,我们都在可以的范围内找个一个最小的sum[j]就是可以了,最后求最大就是了,至于怎么能够快速的找个一个最小的数,我们采用单调队列

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1000005;
const int INF = 0x3f3f3f3f;

int n,k;
int arr[MAXN],sum[MAXN],q[MAXN];

int main(){
	int t;
	scanf("%d", &t);
	while (t--){
		scanf("%d%d", &n, &k);
		for (int i = 1; i <= n; i++){
			scanf("%d", &arr[i]);
			arr[i+n] = arr[i];
		}
		sum[0] = 0;
		for (int i = 1; i <= 2*n; i++)
			sum[i] = sum[i-1] + arr[i];
		int head = 0,tail = 0;
		q[head] = 0;
		int Max = -INF,x,y;
		for (int i = 1; i <= 2*n; i++){
			while (head <= tail && i-q[head]>k)
				head++;
			int j = q[head];
			if (sum[i] - sum[j] > Max){
				Max = sum[i] - sum[j];
				x = j+1;
				y = i;
			}
			while (head <= tail && sum[q[tail]] > sum[i])
				tail--;
			q[++tail] = i;
		}
		if (x > n)
			x -= n;
		if (y > n)
			y -= n;
		printf("%d %d %d\n", Max, x, y);
	}
	return 0;
}



你可能感兴趣的:(HDU - 3415 Max Sum of Max-K-sub-sequence)