Link:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem= 1995
Test instructions
In a straight line there are N (2≤n≤100000) equidistant villages, each of which buys wine or sells liquor.
The demand for wine in the first village is Ai ( -1000≤ai≤1000), of which ai>0 means to buy wine and ai<0 to sell alcohol. The balance of supply and demand in all villages, i.e. all Ai sum equals 0.
Transporting K-units of wine from one village to the neighboring village requires a workforce of k units.
Calculating at least how much labor is needed to meet the needs of all villages. The output is guaranteed to be within the range of 64-bit signed integers.
Analysis:
Problem equivalence conversion.
Consider the left-most village. If you need to buy wine, that is a1>0, there must be a labor force from village 2 left to the village 1,
And no matter where the wine came from (perhaps 2 of the village, perhaps the more right village was transported to the village 2).
In this way, the problem is equivalent to the village 2~n only, and the demand of the 2nd village is a1+a2 situation.
It is not difficult to find out that this reasoning is also established when ai<0 (Labor also needs |ai| units).
Code:
1#include <cstdio>2#include <cstdlib>3 4 intMain () {5 intN;6 while(SCANF ("%d", &n) &&N) {7 intneed;8scanf"%d", &need);9 Long LongLast = need, ans =ABS (need);Ten for(inti =1; I < n; i++){ Onescanf"%d", &need); ALast + =need; -Ans + =ABS (last); - } theprintf"%lld\n", ans); - } - return 0; -}
UVa 11054-wine Trading in Gergovia