您的位置:首页 > 其它

2013. Pay Back

2013-08-18 12:06 441 查看

                                                       2013. Pay BackDescription"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.
[align=left] [/align]InputLine 1: A single integer: N Lines 2..N+1: Line i+1 contains a single integer: D_i
OutputLine 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最少花费的时间

方法:

当且仅当手中的可以还清当前的所有欠款时,立即回头去还清!

将每一步到达的钱累加:

(1)如果刚好从不欠款到欠款,说明目前这点是欠款最少的点,等到一有钱马上回来该点还钱。

(2)如果刚好从欠款过渡到不欠款,说明目前有能力去还钱,马上回头,所走的步数是当前点位置到起点来回减去还钱点位置到起点来回步数,即i+i-p-p;(需要还钱的不仅仅是前面记录下来的那点,沿途可能还有其他需要还钱的点,但不影响结果)

(3)其他情况只需要直接还钱或者直接收钱,因为前面有累加,所以不用再做处理。

#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[100001];
int sum=0;
int p,pace;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int j=0;j<n;j++)
{
sum+=arr[j];
if(sum<0&&sum-arr[j]>=0)//从不欠钱到欠钱的过渡点,记录下来
{
p=j;
}
else if(sum>=0&&sum-arr[j]<0)//从欠钱到不欠钱的过渡点,马上回去还钱
{
pace+=j+j-p-p;  //pace记录回头还钱走过的步数
}
}
pace+=n; //所走过的步数还要加上一路走来的
cout<<pace<<endl;
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心 sicily