2013. Pay Back

                                                       2013. Pay Back
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最少花費的時間

方法:
當且僅當手中的可以還清當前的所有欠款時,立即回頭去還清!
將每一步到達的錢累加:
(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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章