列表

详情


NC24834. [USACO 2009 Mar B]Payback

描述

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

输入描述

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

输出描述

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

示例1

输入:

5
100
-200
250
-200
200

输出:

9

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 32ms, 内存消耗: 612K, 提交时间: 2019-09-13 17:31:38

#include<bits/stdc++.h>
#define MAX_INT  ((unsigned)(-1)>>1)
#define MIN_INT  (~MAX_INT)
#define pi 3.1415926535898
using namespace std;

int main(void)
{
      int n;cin>>n;
      int p=0,num=0;
      int ans=n;
      for(int i=0;i<n;i++){
            int k;cin>>k;
            num+=k;
            if(num<0&&num-k>0) p=i;
            else if(num>=0&&num-k<0)         
            ans+=2*(i-p);
      }
      cout<<ans;
      return 0;
}

C(clang 3.9) 解法, 执行用时: 14ms, 内存消耗: 1124K, 提交时间: 2019-09-07 16:38:43

#include <stdio.h>
int debt[100001];
int main(){
	int n;
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++)
			scanf("%d",&debt[i]);
		int sum=0,step=0,position=0;
		for(int i=0;i<n;i++){
			sum+=debt[i];
			if(sum<0&&sum>debt[i])
				position=i;
			else if(sum>=0&&sum<debt[i])
				step+=2*(i-position);
		}	
		printf("%d\n",step+n);
	}
}

C++11(clang++ 3.9) 解法, 执行用时: 25ms, 内存消耗: 1188K, 提交时间: 2019-09-08 15:23:30

#include <cstdio>
using namespace std;
int money[100005],n,ans,now,pos;
int main(){
  scanf("%d",&n);
  for(int i=0;i<n;++i){
    scanf("%d",&money[i]);
    now+=money[i];
    if(now<0&&now>money[i]){pos=i;}
    else if(now>=0&&now<money[i]){ans+=2*(i-pos);}
  }
  printf("%d",n+ans);
  return 0;
}

上一题