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 E2020 · EasyDigit replacement

Confusing Threes and Eights

National Olympiad — Municipal round (2020 season)

Submission name: wsum.cpp

Problem summary

Given A and B, find the minimum sum after replacing every digit 8 by 3, and the maximum sum after replacing every digit 3 by 8.

Input

Two natural numbers A and B.

Output

The minimum and maximum sums, separated by a space.

Constraints

1 ≤ A,B < 100,000.

Worked example

An independently prepared example for this explanation.

Input

128 33

Output

156 216

Solution analysis

  1. Read each number as a string. Rebuild two integers from left to right, multiplying the current value by ten before appending each digit.
  2. For the minimum version, change only 8 to 3. For the maximum version, change only 3 to 8. Add the two minimum versions and the two maximum versions independently.
  3. For 128 and 33, the smaller versions are 123 and 33, giving 156. The larger versions are 128 and 88, giving 216. Digits other than 3 and 8 remain unchanged.

Why it works

Changing a digit 8 to 3 decreases its place-value contribution and affects no other digit; changing 3 to 8 increases it. Applying every allowed beneficial replacement independently gives the two required extreme sums.

Complexity: O(L) time for L total input digits and O(L) input space; O(1) working space.

Watch out. Do not replace 3 by 8 during the minimum calculation. Compute the two conversions from the original input.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <string>
using namespace std;
int convert(const string& digits, char from, char to) {
    int value = 0;
    for (char digit : digits) {
        if (digit == from) {
            digit = to;
        }
        // Append the transformed digit at its decimal place.
        value = value * 10 + digit - '0';
    }
    return value;
}
int main() {
    string a, b;
    cin >> a >> b;
    int minimum = convert(a, '8', '3') + convert(b, '8', '3');
    int maximum = convert(a, '3', '8') + convert(b, '3', '8');
    cout << minimum << ' ' << maximum << '\n';
}

Source: Arena Olimpiici ↗