问题 I: Sequence

问题 I: Sequence

时间限制: 1 Sec   内存限制: 128 MB
提交: 25   解决: 15
[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

You are given an integer sequence of length N. The i-th term in the sequence is ai. In one operation, you can select a term and either increment or decrement it by one.
At least how many operations are necessary to satisfy the following conditions?
For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.
For every i (1≤i≤n−1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints
2≤n≤105
|ai|≤109
Each ai is an integer.

输入

Input is given from Standard Input in the following format:
n
a1 a2 … an

输出

Print the minimum necessary count of operations.

样例输入

4
1 -3 1 0

样例输出

4

提示

For example, the given sequence can be transformed into 1,−2,2,−2 by four operations. The sums of the first one, two, three and four terms are 1,−1,1 and −1, respectively, which satisfy the conditions.

思路:

维护两钟数组, 正 负 正 负 ,和 负 正 负 正。

具体见代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+10;
ll a[maxn],n,sum,tmp,ans_1=0,ans_2=0;
int main(){
    cin>>n;
    for (int i=1; i<=n ;i++) cin>>a[i];
    sum=0;
    for (ll d,tmp,i=1; i<=n ;i++){
        if(i%2){
            if(sum+a[i]>0) {
                sum+=a[i];
                continue;
            }
            d=abs(sum+a[i])+1;
            ans_1+=d;
            sum=1;
        }
        else {
            if(sum+a[i]<0) {
                sum+=a[i];
                continue;
            }
            d=abs(sum+a[i])+1;
            ans_1+=d;
            sum=-1;
        }
    }
    sum=0;
    for (ll d,tmp,i=1; i<=n ;i++){
        if(i%2==0){
            if(sum+a[i]>0) {
                sum+=a[i];
                continue;
            }
            d=abs(sum+a[i])+1;
            ans_2+=d;
            sum=1;
        }
        else {
            if(sum+a[i]<0) {
                sum+=a[i];
                continue;
            }
            d=abs(sum+a[i])+1;
            ans_2+=d;
            sum=-1;
        }
    }
    cout<<min(ans_1,ans_2)<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值