cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2018 · EasyInteger arithmetic

Water the Flowers

National Olympiad — Regional round (2018 season)

Submission name: flowers.cpp

Problem summary

Water makes each flower grow: q drops add one millimeter to one flower. Given all heights, find the minimum number of drops needed to make every flower equally tall.

Input

n, then n heights in millimeters, then q.

Output

The minimum number of water drops.

Constraints

1 ≤ n ≤ 10000; 1 ≤ height ≤ 10000; 10 ≤ q ≤ 100000000.

Worked example

An independently prepared example for this explanation.

Input

5
10 20 17 12 20
25

Output

525

Solution analysis

  1. Water can only increase heights. Therefore the final common height must be at least the initial maximum height. Choosing exactly that maximum requires the least growth.
  2. The total required growth is n·maximum − sumOfHeights. Multiply this by q to obtain the drop count. Store the sum and the final product in long long.
  3. In the sample the target is 20. The deficits are 10,0,3,8,0 millimeters, totaling 21. At 25 drops per millimeter, 21·25 = 525 drops are needed.

Why it works

Every equalized arrangement has final height H at least the maximum initial height. Its water use is q·(nH−sum), which increases with H. Choosing H equal to the maximum is feasible and minimizes this expression.

Complexity: O(n) time and O(1) extra space.

Watch out. Do not target the average: flowers cannot shrink. The answer can be near 10¹⁶, so 32-bit arithmetic is insufficient.

Commented C++17 solution

An independently written complete program with standard headers.

#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
    int n;
    cin >> n;
    long long sum = 0;
    long long maximum = 0;
    for (int i = 0; i < n; ++i) {
        long long height;
        cin >> height;
        sum += height;
        maximum = max(maximum, height);
    }
    long long q;
    cin >> q;
    // Grow every flower to the current maximum, the least possible target.
    cout << (n * maximum - sum) * q << '\n';
}

Source: Arena Olimpiici ↗