问题 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;
}

posted @ 2018-06-09 22:10  Acerkoo  阅读(253)  评论(0编辑  收藏  举报