Test instructions
Everyone on the street is selling liquor, and every day some people need to sell some wine, and some people need to buy some wine, and then transport a unit of wine between neighboring people needs a unit cost, ask how to arrange people's transactions, can make the total calculation cost is minimal.
Ideas:
Started to think of a greedy idea: obviously every person who needs to buy wine should try to buy his left to sell the wine, no words to buy his right to the nearest wine liquor. The 2nd is good to understand, now to explain the 1th: if the current person does not buy his left to sell the wine and the wine is to be sold anyway, the wine is to be bought by the people on his right, then the price of these wine will inevitably become larger.
In concrete implementation we need to determine whether each person's left is still can buy wine, so if directly through the loop to judge the word is bound to time out (I began to write this once, the result is TL); in fact, we can use an array to record the coordinates of all the liquor-selling people, So we just need to scan this array every time (the element that starts with this array must be the coordinates of the leftmost person who buys the wine), if the item in front of the array is 0, we move the start coordinate to the right (without this step, it will definitely time out).
but just now on the internet to see another one way to do this is not to consider the purchase and sale relationship stipulated in the topic, and to stipulate that the first person buys the wine of the first i+1 person, so the answer is correct, but I still do not know the principle.
The code is as follows:
#include <iostream> #include <cstring> #include <cstdio> #include <cmath>using namespace std;# Define LL long Longint main () {int i,j,k,n,a[110000],b[110000],left; while (scanf ("%d", &n) &&n) {LL sum=0; k=0; for (i=0;i<n;i++) {scanf ("%d", &a[i]); if (a[i]<0) b[k++]=i; } left=0; for (i=0;i<n;i++) {if (a[i]>0) {for (j=left;j<k;j++) {if (a[b[j]]+a[i]<=0) {sum+=a[i]*abs (b[j]-i); A[b[j]]+=a[i]; a[i]=0; if (a[b[j]]==0) left++; Break } else {sum+=-1*a[b[j]]*abs (b[j]-i); A[I]+=A[B[J]]; a[b[j]]=0; left++; }}}} printf ("%lld\n", sum); } return 0;}
Code for another method:
#include <iostream> #include <cstring> #include <cstdio> #include <cmath>using namespace std;# Define LL long Longint main () { int i,j,k,n,a[110000],b[110000],left; while (scanf ("%d", &n) &&n) { LL sum=0; k=0; for (i=0;i<n;i++) scanf ("%d", &a[i]); for (i=0;i<n-1;i++) { sum+=abs (a[i]); A[i+1]+=a[i]; } printf ("%lld\n", sum); } return 0;}
Uva--11054wine trading in Gergovia + greedy