Sicily 2013 Pay Back

Constraints

Time Limit: 1 secs, Memory Limit: 256 MB

Description

"Never a borrower nor a lender be." O how Bessie wishes she had taken that advice! She has borrowed from or lent money to each of N (1 ≤ N ≤ 100,000) friends, conveniently labeled 1..N.


Payback day has finally come. She knows she is owed more money than she owes to the other cows. They have all lined up in a straight line, cow i standing i meters from the barn. Bessie is going to traverse the line collecting money from those who owe her and reimbursing money to those she owes.

As she moves down the line, she can request any cow who owes her money to give her the money. When she has enough money to pay off any or all of her debts, she can pay the (recently collected) money to those she owes. Cow i owes Bessie D_i money (-1,000 ≤ D_i ≤ 1,000; D_i != 0). A negative debt means that Bessie owes money to the cow instead of vice-versa.

Bessie starts at the barn, location 0. What is the minimum distance she must travel to collect her money and pay all those she owes? She must end her travels at the end of the line.

 

Input

Line 1: A single integer: N
Lines 2..N+1: Line i+1 contains a single integer: D_i

Output

Line 1: A single integer that is the total metric distance Bessie must travel in order to collect or pay each cow.

Sample Input

5
100
-200
250
-200
200

Sample Output

9

Problem Source

每周一赛:2010中山大学新手赛


Solution

题意是给出一个序列,分别是欠钱和还钱的数额,在同一条路上,距离是i,问最短把全部债务解决的路的长度。

贪心就好啦,记录下最远一个要还钱的i,一旦有钱(手上总额大于等于0)就去还就ok啦。


#include <cstdio>

int d[100005];

int main()
{
  int i, n, last, sum = 0, ans = 0;

  scanf("%d", &n);
  for (i = 1; i <= n; ++i)
  {
    ++ans;
    scanf("%d", &d[i]);
    if (sum >= 0 && sum + d[i] < 0) last = i;
    if (sum < 0 && sum + d[i] >= 0) ans += 2 * (i - last);
    sum += d[i];
  }
  printf("%d\n", ans);

  return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值