Uva 11054 - Wine trading in Gergovia(模拟)

As you may know from the comic “Asterix andthe Chieftain’s Shield”, Gergovia consists of one street, and every inhabitantof the city is a wine salesman. You wonder how this economy works? Simple enough:everyone buys wine from other inhabitants of the city. Every day eachinhabitant decides how much wine he wants to buy or sell. Interestingly, demandand supply is always the same, so that each inhabitant gets what he wants.There is one problem, however: Transporting wine from one house to anotherresults in work. Since all wines are equally good, the inhabitants of Gergoviadon’t care which persons they are doing trade with, they are only interested inselling or buying a specific amount of wine. They are clever enough to figureout a way of trading so that the overall amount of work needed for transportsis minimized. In this problem you are asked to reconstruct the trading duringone day in Gergovia. For simplicity we will assume that the houses are builtalong a straight line with equal distance between adjacent houses. Transportingone bottle of wine from one house to an adjacent house results in one unit ofwork.

 

Input

The input consists of several test cases.Each test case starts with the number of inhabitants n (2 ≤ n ≤ 100000). Thefollowing line contains n integers ai (−1000 ≤ ai ≤ 1000). If ai ≥ 0, it means that theinhabitant living in the i-th house wants to buy ai bottles of wine, otherwiseif ai < 0, he wants to sell −ai bottles of wine. You mayassume that the numbers ai sum up to 0. The last test case is followed by aline containing ‘0’.

 

Output For each test case print the minimumamount of work units needed so that every inhabitant has his demand fulfilled.You may assume that this number fits into a signed 64-bit integer (in C/C++ youcan use the data type “long long”, in JAVA the data type “long”).

 

Sample Input

5

5 -4 1 -3 1

6

-1000 -1000 -1000 1000 1000 1000

0

 

Sample Output

9

9000

 

【题意】

给定长度为n且总和一定为0的序列,大于0代表出售,小于0代表买入,要求把序列的每一项都变为0,将某个数值x移动到相邻的位置后(比如从i移到i+1,a[i]-x,a[i+1]+x)花费的代价是x,求得一个最小代价来解决整个问题。

 

【思路】

   从左向右模拟计算即可,写完了看看别人的代码真的好简单,有时候自己还是把简单的问题想的复杂了。下面是我自己的代码。

 

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn = 100050;

int n;
int a[maxn];

int main() {
	while (scanf("%d", &n) == 1 && n) {
		for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
		
		ll ans = 0, num;
		int i = 0, flag;
		
		while (1) {
			while (0 == a[i]) { ++i; }
			if (i >= n) break;
			flag = a[i] > 0 ? 1 : -1;
			num = a[i];
			while (num*(ll)flag > 0LL) {
				ans += abs(num);
				num += a[++i];
			}
			if (i >= n) break;
			else a[i] = num;
		}
		
		printf("%lld\n", ans);
	}
	return 0;
}

转载于:https://www.cnblogs.com/wafish/p/10465465.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值