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 E2023 · EasyIntervals & counting

Loading the Fuel Barrels

National Olympiad — Municipal round (2023 season)

Submission name: barrels.cpp

Problem summary

A row contains N1 barrels of one fuel followed by N2 of the other. A means petrol and B means kerosene; both fuel types occur. Load the first K barrels from the left and count the petrol barrels loaded.

Input

N1 C1; N2 C2; then K.

Output

The number of loaded petrol barrels.

Constraints

1 ≤ N1,N2 ≤ 100; 1 ≤ K ≤ N1+N2; C1,C2 are distinct members of {A,B}.

Worked example

An independently prepared example for this explanation.

Input

5 A
6 B
7

Output

5

Solution analysis

  1. The load takes min(K,N1) barrels from the first block. If it reaches the second block, it takes K−N1 barrels from that block.
  2. When the first block is petrol, answer min(K,N1). Otherwise petrol is the second block and the answer is max(0,K−N1).
  3. For 5 A,6 B,K=7, all five petrol barrels and two kerosene barrels are loaded, so answer 5. Reversing the fuel labels makes only the two barrels from the second block petrol.

Why it works

The first K positions overlap the first block in min(K,N1) positions and the second in max(0,K−N1). Selecting the overlap of the petrol-labelled block counts exactly the loaded petrol barrels.

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

Watch out. Fuel A is petrol regardless of which block comes first. Do not count all K barrels when the prefix crosses into kerosene.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int firstCount, secondCount, loaded;
    char firstFuel, secondFuel;
    cin >> firstCount >> firstFuel >> secondCount >> secondFuel >> loaded;
    int petrol;
    // Only the overlap of the loaded prefix with the petrol block counts.
    if (firstFuel == 'A') {
        petrol = min(loaded, firstCount);
    } else {
        petrol = max(0, loaded - firstCount);
    }
    cout << petrol << '\n';
}

Source: Arena Olimpiici ↗