hdu3415
来源:互联网 发布:mac用qq截图 编辑:程序博客网 时间:2024/06/05 03:40
求最大的连续不超过k的子序列的和。
用单调队列维护。
先求出s[1..i]的和,将前k个添加到n的结尾就相当于有循环和了。
那么对于某个sj,他的最大的序列和为s[j] - s[i],其中 j - k - 1 <= i <= j - 1.
那么用单调队列去维护i,可以在O(1)的时间去求出s[i]。
今后有任何优化问题需要减去前面最小或者加上最大和的都可以使用单调队列去维护。
AC代码:
#include <cstdio>#include <cstring>const int MAX_NUMBER = 1000006;const int INF = 2000000007;int sums[2 * MAX_NUMBER];int value[MAX_NUMBER];int queue[2 * MAX_NUMBER];int main() { int test_case; scanf("%d", &test_case); while (test_case--) { int n, length, head, tail, max_number, max_length, start, end; scanf("%d%d", &n, &length); sums[0] = 0; head = tail = 1; queue[head] = 0; max_number = -INF; start = end = MAX_NUMBER; max_length = MAX_NUMBER; for (int i = 1; i <= n; i++) { scanf("%d", &value[i]); sums[i] = sums[i - 1] + value[i]; } for (int i = n + 1; i <= n + length - 1; i++) { sums[i] = sums[i - 1] + value[i % n]; } for (int i = 1; i <= n + length - 1; i++) { while (tail >= head && i - queue[head] > length) { head++; } int temp = sums[i] - sums[queue[head]]; if (temp >= max_number) { if (temp > max_number) { max_number = temp; max_length = i - queue[head]; start = queue[head] + 1; end = i; } else { if (queue[head] + 1 < start) { max_length = i - queue[head]; start = queue[head] + 1; end = i; } else if (queue[head] + 1 == start) { if (max_length > i - queue[head]) { max_length = i - queue[head]; start = queue[head] + 1; end = i; } } } } while (tail >= head && sums[queue[tail]] > sums[i]) { tail--; } queue[++tail] = i; } if (end > n) { end -= n; } printf("%d %d %d\n", max_number, start, end); } return 0;}
- HDU3415
- hdu3415
- HDU3415
- HDU3415
- HDU3415单调队列
- hdu3415 单调队列
- HDU3415单调队列
- hdu3415单调队列
- HDU3415【单调队列】
- HDU3415---单纯的单调队列
- hdu3415 dp最大k字段和
- hdu3415 单调队列求区间最大和
- hdu3415 Max Sum of Max-K-sub-sequence
- hdu3415 Max Sum of Max-K-sub-sequence
- hdu3415 Max Sum of Max-K-sub-sequence
- HDU3415:Max Sum of Max-K-sub-sequence(单调队列)
- hdu3415 Max Sum of Max-K-sub-sequence 单调队列
- hdu3415——Max Sum of Max-K-sub-sequence
- Linux基础知识总结-概述和基本操作
- mysql安装与常用命令
- mac 系统下的音频转换命令
- 算法知识之最长公共子序列问题(动态规划)
- Android4.3 Bluetooth 抓取hci log
- hdu3415
- PPT演示器(3.3.1)是如何的
- 冬季养生注意!
- Cannot find or open the PDB file
- 对中级 Linux 用户非常有用的 20 个命令
- -XX:MaxPermSize=512m
- jQuery之addClasas与removeClass使用实例
- 如何定位安卓程序关键代码
- SVN服务器搭建和使用(一)