Painted Faces of Unit Cubes
National Olympiad — Regional round (2013 season)
Submission name: painting.cpp
Problem summary
A w-by-h-by-l block of unit cubes has every exterior face painted. Count unit cubes with exactly k painted faces, allowing dimensions equal to 1.
Input
w h l k.
Output
The number of cubes with exactly k painted faces.
Constraints
1 ≤ w,h,l ≤ 100; 0 ≤ k ≤ 6.
Worked example
Input and output for the worked example discussed below.
Input
3 1 1 4
Output
1
Solution analysis
- Inspect each unit cube by its three coordinates. Its left face is painted when x=0 and right face when x=w−1. Apply the same two boundary tests to y and z.
- The six tests must be independent. If w=1, the same cube touches both opposite exterior faces in that dimension and earns two painted faces. Treating these conditions as if/else would lose one.
- For a 3-by-1-by-1 block, the middle cube has both y faces and both z faces painted, exactly four. The two end cubes also have one x face painted and have five. The requested k=4 count is therefore 1.
Why it works
A face is exterior exactly when the cube lies at the corresponding coordinate boundary. The six independent indicator tests therefore count exactly its painted faces. Every unit cube is enumerated once, so the final indicator sum gives precisely the requested count.
Watch out. Usual corner/edge/face formulas assuming all dimensions exceed 1 fail for thin blocks. A cube may have more than three painted faces. Count both opposite faces separately.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
using namespace std;
int main(){
int w;
int h;
int l;
int k;
cin>>w>>h>>l>>k;
int answer=0;
for(int x=0;x<w;x++){
for(int y=0;y<h;y++){
for(int z=0;z<l;z++){
// Independent tests correctly handle a dimension of length one.
int painted=(x==0)+(x==w-1)+(y==0)+(y==h-1)+(z==0)+(z==l-1);
answer+=painted==k;
}
}
}
cout<<answer<<'\n';
}