cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2018 · MediumBounded-state simulation

Bacteria after an Enormous Number of Days

National Olympiad — Municipal round (2018 season)

Submission name: bact.cpp

Problem summary

Start with A bacteria. Each day every bacterium is replaced by B, C bacteria are removed, and the remainder is capped at D. If too few remain for removal the experiment ends. Find the count after K days.

Input

A B C D K.

Output

The final count, or0 if the experiment has ended.

Constraints

0 ≤ A,B,C,D ≤1000; A≤D;1 ≤ K ≤10^18.

Worked example

Input and output for the worked example discussed below.

Input

1 3 1 5 2

Output

5

Solution analysis

  1. One day maps x to f(x)=min(D,max(0,Bx−C)). Zero is absorbing, including the case where exactly C bacteria are removed and none remain.
  2. Although K is huge, f is nondecreasing. If the first step increases x, later steps can never decrease it; if it decreases x, later steps can never increase it. An integer orbit bounded between0 and D therefore changes at most D times before stabilizing.
  3. Simulate until K days have passed or next equals current. At a fixed point every remaining day leaves the count unchanged. The sample goes1→2→5, so day2 has5 bacteria.

Why it works

Monotonicity of f preserves the initial direction of change by induction. A bounded monotone integer sequence must reach a fixed point after at most D changes. Direct simulation is exact before that point, and returning the fixed value is exact for all remaining days.

Complexity: O(min(K,D+1)) time and O(1) space. Products xB are at most10^6.

Watch out. Do not loop up to10^18 or forget the daily cap. Use a64-bit day limit and stop only at a genuine fixed point.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<iostream>
using namespace std;
int main(){
    int count;
    int multiplier;
    int removed;
    int capacity;
    long long days;
    cin>>count>>multiplier>>removed>>capacity>>days;
    for(long long day=0;day<days;day++){
        int next=min(capacity,max(0,count*multiplier-removed));
        // A fixed point persists for every remaining day.
        if(next==count){
            break;
        }
        count=next;
    }
    cout<<count<<'\n';
}

Source: Arena Olimpiici ↗