zoukankan      html  css  js  c++  java
  • 问题 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;
    }
    

  • 相关阅读:
    Symmetric Order
    Red and Black
    Sticks(递归经典)
    Pascal Library
    cantor的数表
    OJ 调试技巧:VS2010 中 通过设置编译参数定义宏,无需修改源文件重定向标准输入输出
    strcmp
    最短周期串
    字母重排
    codeblocks 单步调试
  • 原文地址:https://www.cnblogs.com/acerkoo/p/9490314.html
Copyright © 2011-2022 走看看