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;
}

posted @ 2017-12-26 22:46  不想吃WA的咸鱼  阅读(130)  评论(0编辑  收藏  举报