您的位置:首页 > 其它

Sicily 2013. Pay Back

2013-09-09 17:42 381 查看


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


题意解析:Bessie欠一些人钱,也有一些人欠Bessie的钱。Bessie在原点,也就是x=0,而其他共n个人恰好住在x=1,2,3,…,n处。Bessie现在从家出发,要到把别人欠的债收回来,并用收回来的钱还清欠别人的债,并到达x=n处。问Bessie走过的最少距离。

思路:Bessie从原点x=0处出发,最终一定会到达x=n,所以只需要算出Bessie在途中多走的距离d,最后加上n就可以。

          

代码如下:

#include<iostream>
using namespace std;

int main()
{
int n,m;
int sum=0;//sum记录目前手上的钱数
int d=0;
int p=0; //p记录当前所有欠钱地点的最小值
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>m;
sum+=m;
//从不欠钱到欠钱,即该点当前为所有欠钱地点的最小值
if((sum-m>0||sum-m==0)&&sum<0)p=i;
//从欠钱到不欠钱,即有能力还清前面的欠款,立即去还
else if(sum-m<0&&(sum==0||sum>0))
d+=(i-p)*2;
}
cout<<d+n<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sicily 贪心