Answer to Question 22A-6
#include <cstdio>
#include <algorithm>
using namespace std;
//=======================================================
// InstallBuilding
//=======================================================
// Install a building given by
// left boundary L
// right boundary R
// height H
// into the skyline array.
//
// Parameter n is the number of positions in the skyline
// array.
//=======================================================
void InstallBuilding(int* skyline, const int L, const int R,
const int H, const int n)
{
int left = max(L, 0);
int right = min(L, n-1);
for(int i = left; i < right; i++)
{
skyline[i] = max(skyline[i], H);
}
}
//=======================================================
// InstallBuildings
//=======================================================
// Read the building descriptions and store them into
// array skyline, where skyline[i] is the height of the
// skyline from horizontal position i to position i+1.
//
// Parameter n is the number of positions in the skyline
// array.
//=======================================================
void InstallBuildings(int* skyline, const int n)
{
int L, R, H;
scanf("%d", &L);
while(L != 0)
{
scanf("%d%d", &R, &H);
InstallBuilding(skyline, L, R, H, n);
}
}
//=======================================================
// ShowSkyline
//=======================================================
// Write out the skyline stored in array skyline, of
// size n.
//=======================================================
void ShowSkyline(const int* skyline, const int n)
{
for(int i = 0; i < n; i++)
{
printf("%d\n", skyline[i]);
}
}
int main()
{
const int numPositions = 100;
int skyline[numPositions];
InstallBuildings(skyline);
InstallBuildings(skyline, numPositions);
ShowSkyline(skyline, numPositions);
}