cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2021 · EasyGeometry

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

  1. 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.
  2. 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.
  3. 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.

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

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';
}

Source: Arena Olimpiici ↗