There are n equidistant villages in a straight line, and each village either buys wine or sells alcohol. Transporting K-units of wine from one village to the neighboring village requires a workforce of k units. Ask at least how much labor is needed to meet the needs of all villages
Thinking greedy
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream > #include <algorithm> #include <vector> #include <map> #include <queue> #include <stack& Gt #include <string> #include <map> #include <set> #define EPS 1e-6 #define LL Long long using namespace std; const int MAXN = 100000 + 100;const int INF = 0x3f3f3f3f;//freopen ("Input.txt", "R", stdin); int C[MAXN], n;int lowbit (int x) {return x& (-X);} int sum (int x) {if (x = = 0) return 0;int ret = 0;while (x > 0) {ret + = c[x]; x-= Lowbit (x);} return ret;} void Add (int x, int d) {while (x <= N) {c[x] + = D; x + = Lowbit (x);}} ll solve (int left, int. right) {if (left = right) return (LL) 0;if (left+1 = = right) return (LL) ABS (SUM (right)-sum (left)); int Mid = (left + right) >> 1;int tmp = SUM (mid)-sum (left-1); Add (Mid,-tmp); Add (mid+1, TMP), return solve (left, mid) + solve (mid+1, right) + (LL) ABS (TMP); }void init () {memset (C, 0, sizeof (C)); int tmp;for (int i = 1; I <= n; i++) {cin >> tmp;add (i, TMP);}} int main () {//freopen ("Input.txt", "R", stdin), while (scanf ("%d", &n) = = 1 && N) {init (); cout << solve (1, n) << Endl;} return 0;}
UVA 11054 Gerovia Wine Trading (greedy + tree-like array)