您的位置:首页 > 其它

Sicily 2013. Pay Back

2012-02-10 00:03 232 查看
一个欠债还钱、借债讨钱的问题,贪心算法解决。

沿着路一直走下去,把别人欠的钱都拿回,把能还的钱还了。当手头上的钱不够还时,记下当前编号。然后往后走,只收钱不还钱,等到收到的钱能够一次还清前面所欠的钱的总和时,往回走,边走边还钱,还完钱再往前走。如此反复,直到终点即可。另外要注意统计走过的路程。

Run Time: 0.03sec

Run Memory: 304KB

Code length: 769Bytes

Submit Time: 2011-12-08 00:39:23

// Problem#: 2013
// Submission#: 1049990
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
using namespace std;

int main()
{
int N, i;
int money, keep;
int dist = 0, total = 0, lend = 0;
bool unable = false;

scanf( "%d", &N );
for ( i = 0; i < N; i++ ) {
scanf( "%d", &money );
if ( money > 0 ) {
total += money;
if ( unable && total >= -lend ) {
total += lend;
lend = 0;
unable = false;
dist += ( i - keep ) * 2;
}
}
else if ( unable )
lend += money;
else if ( -money <= total )
total += money;
else {
unable = true;
keep = i;
lend += money;
}
}
printf( "%d\n", dist + N );

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: