博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Non-negative Partial Sums(单调队列)
阅读量:5989 次
发布时间:2019-06-20

本文共 2186 字,大约阅读时间需要 7 分钟。

Non-negative Partial Sums

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 2622    Accepted Submission(s): 860

Problem Description
You are given a sequence of n numbers a
0,..., a
n-1. A cyclic shift by k positions (0<=k<=n-1) results in the following sequence: a
k a
k+1,..., a
n-1, a
0, a
1,..., a
k-1. How many of the n cyclic shifts satisfy the condition that the sum of the first i numbers is greater than or equal to zero for all i with 1<=i<=n?
 

 

Input
Each test case consists of two lines. The first contains the number n (1<=n<=10
6), the number of integers in the sequence. The second contains n integers a
0,..., a
n-1 (-1000<=a
i<=1000) representing the sequence of numbers. The input will finish with a line containing 0.
 

 

Output
For each test case, print one line with the number of cyclic shifts of the given sequence which satisfy the condition stated above.
 

 

Sample Input
3 2 2 1 3 -1 1 1 1 -1 0
 

 

Sample Output
3 2 0
题解:给n个数,a0,a1,...an,求ai,ai+1,...an,a1,a2,...ai-1这样的排列种数,使得所有的前k(1<=k<=n)个的和都大于等于0;

求前缀和,加倍序列。

要满足前k个和都>=0,只需最小值>=0,所以用单调队列维护一个最小的前缀和sum[i],(i>=j-n+1),这样就保证了sum[j]-sum[i]最大,所以区间【j-n+1,i]最小。

维护一个单调队列代表终止位置的最小值从小到大;
代码:
#include
#include
#include
#include
#include
using namespace std;const int MAXN = 1e6 + 100;int num[MAXN];int sum[MAXN];int q[MAXN];int main(){ int n; while(~scanf("%d", &n), n){ sum[0] = 0; for(int i = 1; i <= n; i++){ scanf("%d", num + i); sum[i] = sum[i - 1] + num[i]; } for(int i = n + 1; i <= 2*n; i++) sum[i] = sum[i - 1] + num[i - n]; // for(int i = 0; i <= 2*n; i++) // printf("%d ", sum[i]);puts(""); int head = 0, tail = -1, ans = 0; for(int i = 1; i <= 2 * n; i++){ while(head <= tail && sum[i] < sum[q[tail]])tail--; q[++tail] = i; // printf("i = %d %d %d\n", i, sum[q[head]], sum[i - n]); if(i > n && sum[q[head]] - sum[i - n] >= 0)ans++; while(head <= tail && q[head] <= i - n)head++; } printf("%d\n", ans); } return 0;}

 

转载地址:http://tunlx.baihongyu.com/

你可能感兴趣的文章
JVM参数设置
查看>>
如何解决 Java 安全问题?
查看>>
获取启动程序的退出码
查看>>
【Visual C++】关于无法打开包括文件:“StdAfx.h”或者意外结尾的错误解决方案
查看>>
访问网络文件系统
查看>>
iptable之SNAT的实现
查看>>
感觉自己好不努力啊。
查看>>
string
查看>>
空格并不是空白
查看>>
深入源码分析Handler的消息处理机制
查看>>
js中几种实用的跨域方法原理详解
查看>>
分布式架构真正适用于大型互联网项目的架构! dubbo+zookeeper+springmvc+mybatis+shiro+redis...
查看>>
Linux下查看、关闭及开启防火墙命令
查看>>
腾讯云技术分享:MySQL AHI 实现解析
查看>>
mysql_master__(mysql_relay)__(mysql_slave)
查看>>
centos7 syslog-ng错误总结
查看>>
JAVA利用第三方平台发送短信验证码。
查看>>
腾讯技术工程 | 腾讯大数据发布2017第三季度移动行业数据报告
查看>>
小编带着小白看springboot源码
查看>>
(1)多线程之Object方法概述
查看>>