Garden Border
Autumn Tournament (2021)
Submission name: garden.cpp
Problem summary
A flowerbed consists of two axis-aligned rectangles stacked vertically with their left edges aligned. Their widths and heights are w1, h1 and w2, h2. Surround the entire bed with a one-cell-thick border of unit square tiles, including the outside corner tiles as in the statement diagram. Find the number of tiles.
Input
Four integers w1, h1, w2, h2, each on its own line.
Output
The number of unit tiles in the border.
Constraints
1 ≤ w1, h1, w2, h2 ≤ 100000000.
Worked example
Original statement, example 1.
Input
2 2 4 2
Output
20
Solution analysis
- Let H = h1 + h2 and W = max(w1, w2). The exposed horizontal edge lengths sum to 2W: the top, bottom, and width difference at the step. The vertical edge lengths sum to 2H.
- A unit-cell border around this rectilinear shape contains the perimeter plus four tiles. At outward corners extra corner tiles appear; at the inward step one overlap cancels one of them, leaving four in total. Thus the answer is 2(W + H) + 4.
- For widths 2 and 4 and heights 2 and 2, W = 4 and H = 4, so 2(4 + 4) + 4 = 20 tiles. Equal widths also work: the bed is then an ordinary rectangle.
Why it works
For equal widths the rectangular ring has 2W + 2H + 4 cells. If widths differ by d > 0, the right side of the narrower rectangle shifts inward by d cells. The ring loses d tiles along the far horizontal edge and gains d along the step, so its size remains 2W + 2H + 4.
Watch out. This is a border of square tiles, not merely the geometric perimeter. Include the four extra corner cells.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
long long w1,h1,w2,h2;
cin>>w1>>h1>>w2>>h2;
// The step does not change the total from the bounding perimeter plus four.
cout<<2*(max(w1,w2)+h1+h2)+4<<'\n';
}