解题报告 之 UVA11054 Wine trading in Gergovia

来源:互联网 发布:江苏网络协会 编辑:程序博客网 时间:2024/06/05 03:16

解题报告 之 UVA11054 Wine trading in Gergovia

Description

Download as PDF

As you may know from the comic "Asterix and the Chieftain's Shield", Gergovia consists of one street, and every inhabitant of 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 each inhabitant decides how much wine he wants to buy or sell. Interestingly, demand and supply is always the same, so that each inhabitant gets what he wants.

There is one problem, however: Transporting wine from one house to another results in work. Since all wines are equally good, the inhabitants of Gergovia don't care which persons they are doing trade with, they are only interested in selling or buying a specific amount of wine. They are clever enough to figure out a way of trading so that the overall amount of work needed for transports is minimized.

In this problem you are asked to reconstruct the trading during one day in Gergovia. For simplicity we will assume that the houses are built along a straight line with equal distance between adjacent houses. Transporting one bottle of wine from one house to an adjacent house results in one unit of work.

Input Specification

The input consists of several test cases. Each test case starts with the number of inhabitants n (2 ≤ n ≤ 100000). The following line contains n integers ai (-1000 ≤ ai ≤ 1000). If ai ≥ 0, it means that the inhabitant living in the ith house wants to buy ai bottles of wine, otherwise if ai < 0, he wants to sell -aibottles of wine. You may assume that the numbers ai sum up to 0.
The last test case is followed by a line containing 0.

Output Specification

For each test case print the minimum amount 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++ you can use the data type "long long", in JAVA the data type "long").

Sample Input

55 -4 1 -3 16-1000 -1000 -1000 1000 1000 10000

Sample Output

99000
题目大意:有n个相互有交易的酒馆,每个酒馆有多余的酒要卖或者需要买酒,输入每个酒馆的酒数(大于0表示有余量,小于0表示有需求)。保证各个酒馆之间供需平衡。且将k桶酒运到相同酒馆需要k个劳动力,问一共需要多少个劳动力。
此题注意要把负数当做证书来看。首先分析第一个酒馆,无论它的酒量k是正数还是负数,它都要向相邻的酒馆运送出/入k个酒(即无论如何都要消耗k个劳动力)。然后我们看第二个,此时它先收到了来自一的运送/订单,并完成这笔交易,然后它剩下的酒量k*又必须向第三个酒庄运送出/入。以此类推,则只需要扫描一遍,更新运送到当前酒馆右边的总量即可。
下面上代码:
#include<iostream>using namespace std;int main(){int n;while (cin >> n&&n){long long  num,last=0,ans=0;for (int i = 0; i < n; i++){cin >> num;last += num;ans += abs(last);}cout << ans<<endl;}}

今天都是水题效率好高的样子~~哈哈哈哈
0 0