1642: 【USACO】Payback(还债)
时间限制: 1 Sec 内存限制: 64 MB
提交: 190 解决: 95
[提交] [状态] [讨论版] [命题人:外部导入]
题目描述
"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.
/*
"决不借别人钱也不借钱给别人。" 贝茜希望自己能遵守这个忠告! 她从N(1 <= N <= 100,000)个朋友那借了钱或借钱给他们,这些朋友编号为1..N。 还清债务的日子到了。她知道她借给别人的钱比她欠别人的钱多。他们全部排成了一条直线,奶牛i站在距离谷仓i米的地方。贝茜要穿过这条直线来索要她的钱并还清她的债务。
当她走过某一头牛时,她可以请求欠她钱的牛还她钱。当她有足够多的钱还清任一头牛或所有牛的债务时,她可以去还钱。奶牛i与贝茜的债务为D_i(-1,000 <= D_i <= 1,000; D_i != 0)。正整数表示奶牛i欠贝茜钱,反之则是贝茜欠他们钱。 贝茜一开始呆在谷仓,位置号为0。编一个程序计算出她收还所有债务必须移动的最小距离。她最后必须站在这条直线上的最后一头牛那。
*/
输入
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains a single integer: D_i
/*
* 第1行: 一个单精度整数: N
* 第2..N+1行: 行i+1表示一个单精度整数: 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
提示
INPUT DETAILS: Three cows owe Bessie; she owes two. When she's done, Bessie will have 150 money.
/*
输入说明: 三头牛欠贝茜钱; 她欠两头牛钱。当她收还完债务时,有150元钱。
*/
OUTPUT DETAILS:(输出说明:)
来源/分类
USACO 2009 March Bronze
题解如下
#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int ar[n+1];
ar[0]=0;
for(int i=1;i<n+1;i++)
{
scanf("%d",&ar[i]);
}
int sum_money=0;
int owe_money=0;
int sum_distance=0;
int flag_pos=99999999;
for(int i=1;i<=n;i++)
{
sum_distance++;
if(ar[i]>0)
{
sum_money+=ar[i];
if(sum_money>=-owe_money&&owe_money!=0)
{
sum_money+=owe_money;
sum_distance+=2*(i-flag_pos);
flag_pos=9999999;
owe_money=0;
}
}
else if(ar[i]<0)
{
if(sum_money>=-ar[i])
{
sum_money+=ar[i];
ar[i]=0;
}
else
{
if(flag_pos>i)
flag_pos=i;
owe_money+=ar[i];
}
}
}
printf("%d",sum_distance);
return 0;
}
今天的文章1642: 【USACO】Payback(还债)[通俗易懂]分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/66541.html