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 D2012 · EasyArithmetic indexing

Serpentine Tree Numbering

National Olympiad — Regional round (2012 season)

Submission name: limes.cpp

Problem summary

Trees form an n-by-m grid numbered from zero in alternating left-to-right and right-to-left rows. Find the tree number at the given 1-based row x and column y.

Input

n m x y.

Output

The zero-based tree number.

Constraints

1 ≤ n,m ≤ 100; 1 ≤ x ≤ n; 1 ≤ y ≤ m.

Worked example

Input and output for the worked example discussed below.

Input

5 2 3 1

Output

4

Solution analysis

  1. The first x−1 rows contain exactly (x−1)m trees. This is the first number reserved for row x, independent of its direction.
  2. Odd 1-based rows run left to right, so their offset is y−1. Even rows run right to left, so their offset is m−y. Add the correct offset to the row’s first reserved number.
  3. For n=5,m=2,x=3,y=1, two complete rows reserve numbers 0…3. Row 3 goes left to right, and its first tree therefore has number 4. No grid construction is needed.

Why it works

Each earlier row contributes m consecutive labels. The offset formulas enumerate the current row’s m labels in exactly the required direction, so the computed number is the unique label at (x,y).

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

Watch out. Coordinates start at 1 but labels start at 0. Reverse even rows, not odd rows. The unused n still belongs to the input.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
using namespace std;
int main(){
    int n;
    int m;
    int x;
    int y;
    cin>>n>>m>>x>>y;
    // Labels begin at zero, while the requested coordinates begin at one.
    int offset=x%2==1?y-1:m-y;
    cout<<(x-1)*m+offset<<'\n';
}

Source: Arena Olimpiici ↗