Non-negative Partial Sums(单调队列,好题)

Non-negative Partial Sums

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2252    Accepted Submission(s): 773



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 fi rst 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 fi rst 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 题解: 题目最后会转化为动态区间求最小值问题,而这类问题单调队列完全可以秒杀其它所有算法(在我所知的算法下),而且这道题目卡空间,其它一些算法,     比如RMQ都没法做,这就体现单调队列的好处所在了,时间复杂度和空间复杂度都是O(n); 在这里给大家一个链接,单调队列讲得不错。 点击打开链接 代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <queue>
#include <map>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <set>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e6 + 100;

struct Node
{
    int sum,id;
    void init(int i)
    {
        sum = 0;
        id = i;
    }
}a[N];
int b[N],n;
deque<Node> que,qu;

void make()
{
    for(int i = 1; i <= n; i++)
    {
        if(que.size() == 0)
            que.push_back(a[i]);
        else
        {
            while(que.size() && que.back().sum > a[i].sum) que.pop_back();
            que.push_back(a[i]);
        }
    }
}

int main()
{
    while(~scanf("%d",&n) && n)
    {
        a[0].init(0);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d",&b[i]);
            a[i].init(i);
            a[i].sum += a[i - 1].sum + b[i];
        }
        que = qu;
        make();
        int sum,ans;
        sum = ans = 0;
        for(int i = 1; i <= n; i++)
        {
            while(que.size() && que.front().id < i) que.pop_front();
            if(que.front().sum - sum >= 0) ans++;
            sum += b[i];
            Node nx;
            nx.init(i + n);
            nx.sum += a[n].sum + sum;
            while(que.size() && que.back().sum > a[n].sum + sum) que.pop_back();
            que.push_back(nx);
        }
        printf("%d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值