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
- The first x−1 rows contain exactly (x−1)m trees. This is the first number reserved for row x, independent of its direction.
- 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.
- 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).
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';
}