cppAcademy
FROM LEARNING TO COMPETING

Real problems.
Your next challenge.

Explore the Group C Olympiad archive.
Choose a topic. Find a challenge. Build your solution.

213 tasks across the Municipal, Regional, and National rounds (2009–2026), plus 4 previously featured problems. 146 tasks have independently written English summaries, analyses, and C++17 solutions; the remaining entries link to Arena. Topic tags are from Arena or our reviewed explanations. Difficulty labels are learning estimates, not official ratings.
GROUP C2013 · MediumMulti Source Bfs

Virus Spread

National Olympiad — Regional round

Submission name: viruses.cpp

Problem summary

In an n-by-m grid, k initially infected cells spread infection to their four orthogonal neighbors every unit of time, simultaneously. Find when every cell is infected.

Input

n m, then k and k pairs of 1-based row and column coordinates.

Output

The required number of time units.

Constraints

1 ≤ n,m ≤ 3000; 1 ≤ k ≤ 10; coordinates lie inside the grid.

Worked example

An independently prepared example for this explanation.

Input

3 3
1 2 2

Output

2

Solution analysis

  1. For each cell compute its minimum Manhattan distance to the initial infected cells.
  2. The largest such minimum is the last infection time. This avoids allocating a queue for nine million cells.

Why it works

An infection needs at least Manhattan distance to reach a cell, and a shortest grid path achieves that time. The first arriving infection determines each cell’s time.

Complexity: O(nmk) time, O(k) space.

Watch out. Sources spread simultaneously; do not add their distances.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: An infection needs at least Manhattan distance to reach a cell, and a shortest grid path
// achieves that time. The first arriving infection determines each cell’s time.
#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<cmath>
#include<climits>
#include<cstdlib>
#include<iterator>
using namespace std;
int main(){
    int n,m,k;
    cin>>n>>m>>k;
    vector<pair<int,int>>a(k);
    for(auto&[x,y]:a){
        cin>>x>>y;
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            int best=INT_MAX;
            for(auto[x,y]:a){
                best=min(best,abs(i-x)+abs(j-y));
            }
            ans=max(ans,best);
        }
    }
    cout<<ans<<'\n';
}

Source: Arena Olimpiici ↗