NC24834. [USACO 2009 Mar B]Payback
描述
输入描述
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer:
输出描述
* 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; }