(UVA

来源:互联网 发布:汉王手写板软件下载 编辑:程序博客网 时间:2024/06/11 19:09

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
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 i-th house wants to buy ai bottles of wine, otherwise if ai < 0,
he wants to sell −ai bottles 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
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
5
5 -4 1 -3 1
6
-1000 -1000 -1000 1000 1000 1000
0
Sample Output
9
9000

题意:直线上有n个村庄(2<=n<=10^5)个等距的村庄每个村庄要么买酒要么卖酒。设第i个村庄对酒的需求为ai(-1000<=ai<=1000),其中ai>0表示买酒,ai<0表示卖酒。所有的村庄的需求之和为0.
把k个单位的酒从一个村庄运到相邻村庄需要k个劳动力。计算最少需要多少劳动力可以满足所有村庄的需求?

分析:考虑最左边的村庄。 如果买酒,即a1>0,那么一定有劳动力从村庄2往左运到1,不管酒来自与哪儿。
这样,问题等价于只有村庄2-n,且第二个村庄需求为a1+a2。 当a1<0时也成立。

#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<cmath>#include<iostream>using namespace std;#define mem(a,n) memset(a,n,sizeof(a))typedef long long LL;const int INF=0x3f3f3f3f;const int N=1e5+5;int main(){    int n,x;    while(~scanf("%d",&n)&&n)    {        LL last=0,ans=0;        for(int i=0;i<n;i++)        {            scanf("%d",&x);            ans+=abs(last);            last+=x;        }        printf("%lld\n",ans);    }    return 0;}
原创粉丝点击