标签:单调队列
4 6 3 6 -1 2 -6 5 -5 6 4 6 -1 2 -6 5 -5 6 3 -1 2 -6 5 -5 6 6 6 -1 -1 -1 -1 -1 -1
7 1 3 7 1 3 7 6 2 -1 1 1
#include <map> #include <set> #include <list> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 200010; int dp[N], arr[N]; int in_que[N], sum[N]; int main() { int n, t, k; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &k); sum[0] = 0; for (int i = 1; i <= n; ++i) { scanf("%d", &arr[i]); sum[i] = sum[i - 1] + arr[i]; } for (int i = n + 1; i < 2 * n; ++i) { sum[i] = sum[i - 1] + arr[i - n]; } int front = 0, rear = 0; int s, e, maxs = -0x3f3f3f3f; for (int i = 1; i <= k; ++i) { while (front < rear && sum[in_que[rear - 1]] >= sum[i - 1]) { rear--; } in_que[rear++] = i - 1; // printf("%d %d\n", sum[in_que[front]], sum[i]); if (maxs < sum[i] - sum[in_que[front]]) { maxs = sum[i] - sum[in_que[front]]; s = in_que[front] + 1; e = i; } else if (maxs == sum[i] - sum[in_que[front]] && in_que[front] + 1 < s) { s = in_que[front] + 1; } else if (maxs == sum[i] - sum[in_que[front]] && in_que[front] + 1 == s && e > i) { e = i; } // printf("%d\n", in_que[front]); } for (int i = k + 1; i < 2 * n; ++i) { while (front < rear && sum[in_que[rear - 1]] >= sum[i - 1]) { rear--; } in_que[rear++] = i - 1; if (in_que[front] < i - k) { front++; } if (maxs < sum[i] - sum[in_que[front]]) { maxs = sum[i] - sum[in_que[front]]; s = in_que[front] + 1; e = i; } else if (maxs == sum[i] - sum[in_que[front]] && in_que[front] + 1 < s) { s = in_que[front] + 1; } else if (maxs == sum[i] - sum[in_que[front]] && in_que[front] + 1 == s && e > i) { e = i; } } if (s > n) { s -= n; } if (e > n) { e -= n; } printf("%d %d %d\n", maxs, s, e); } return 0; }
hdu3415——Max Sum of Max-K-sub-sequence
标签:单调队列
原文地址:http://blog.csdn.net/guard_mine/article/details/41726707