UVA 11054 Gerovia Wine Trading (greedy + tree-like array)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.