您的位置:首页 > 产品设计 > UI/UE

AtCoder Beginner Contest 059 C - Sequence(贪心)

2017-04-22 23:47 441 查看


C - Sequence

Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

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

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


Output

Print the minimum necessary count of operations.

Sample Input 1

Copy
4
1 -3 1 0


Sample Output 1

Copy
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.

Sample Input 2

Copy
5
3 -6 4 -5 7


Sample Output 2

Copy
0

The given sequence already satisfies the conditions.

Sample Input 3

Copy
6
-1 4 3 2 -5 4


Sample Output 3

Copy
8


题目大意:给n个数字组成的数组,可以对任何数字进行删减添加,每次删减添加1为一次操作步数,问满足以下两个条件下,最小操作次数

1.要求1-i个数字和不为0,1<=i<=n

2.要求1-(i-1)的和与i的正负相反,也就是说,当前i-1个数字为正数时候,要求加上第i个数字后,之后为负数

解题思路:这个就是当某个数不符合条件的时候,尽可能的使得和为-1或者1,这样才能让操作次数尽可能的小,考虑到这种情况,1到n只可能是正负正负正负,或者负正负正负正两种情况,同时判断,取个最小值,同时要注意的是,当第一个数是0的时候的处理,WA了无数发才发现对第一个数为0的设定不符合情况就尴尬了

#include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>
#include<cstdio>
#include<climits>
#include<cmath>
#include<vector>
#include <bitset>
#include<algorithm>
#include <queue>
#include<map>
#include<stack>
using namespace std;

long long int ans1, ans2, sum1, sum2;
int n, i;
long long int a[100005];
int main()
{
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
if (a[1] >0)
{
sum1 = a[1];
ans2= a[1] + 1;
sum2 = -1;
}
else if (a[1] == 0)
{
sum1 = 1;
ans1 = ans2 = 1;
sum2 = -1;
}
else
{
sum1 = 1;
ans1 = abs(a[1]) + 1;
sum2 = a[1];
}
for (i = 2; i <= n; i++)
{
if (sum1 > 0)
{
if (a[i] + sum1 >= 0)
{
ans1 += a[i] + sum1 + 1;
sum1 = -1;
}
else
{
sum1 += a[i];
}
}
else
{
if (a[i] + sum1 <= 0)
{
ans1 += abs(sum1 + a[i]) + 1;
sum1 = 1;
}
else
{
sum1 += a[i];
}
}
}
if (sum1 == 0)
{
ans1++;
}
for (i = 2; i <= n; i++)
{
if (sum2 > 0)
{
if (a[i] + sum2 >= 0)
{
ans2 += a[i] + sum2 + 1;
sum2 = -1;
}
else
{
sum2 += a[i];
}
}
else
{
if (a[i] + sum2 <= 0)
{
ans2 += abs(sum2 + a[i]) + 1;
sum2 = 1;
}
else
sum2 += a[i];
}
}
if (sum2 == 0)
{
ans2++;
}
cout << min(ans1, ans2) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: