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

  • 相关阅读:
    第 15 章 标签页和工具提示插件
    第 14 章 下拉菜单和滚动监听插件
    第 13 章 模态框插件
    第 12 章 列表组面板和嵌入组件
    第 11 章 进度条媒体对象和 Well 组件
    第 10 章 巨幕页头缩略图和警告框组件
    第 9 章 路径分页标签和徽章组件
    lock()与lockInterruptibly()的区别
    MySQL中Innodb的聚簇索引和非聚簇索引
    MySQL使用可重复读作为默认隔离级别的原因
  • 原文地址:https://www.cnblogs.com/acerkoo/p/9490314.html
Copyright © 2011-2022 走看看