Building Problem – Dynamic Programming Solutions

This is a C++ Program that Solves Building Problem using Dynamic Programming technique.

Problem Description

There are n plots in a row. Buildings are to be constructed on these plots in such a way that there is space between every two buildings. Find the number of ways in which buildings can be constructed in the plots.

Problem Solution

This is a very simple problem if you observe it carefully. The solution to this problem is simply (n+2)th fibonacci number.

advertisement

Expected Input and Output

Case-1:

n=1
ways=2 either build here or not

Case-2:

advertisement

n=2
ways=3 (both empty, only first empty, only second empty)

Program/Source Code

Here is source code of the C++ Program to Solve Building Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

#include<iostream>

usingnamespace std;

//this function returns the (n+2)th fibonacci number

int buildingProblem(int n)

{

int first=1, second=1;

int j;

for(int i=1;i<=n;i++)

{

j=first;

first=second;

second+=j;

}

return second;

}

int main()

{

int n;

cout<<"Enter the number of plots ";

cin>>n;

cout<<"The number of ways in which buildings can be constructed with the given constraints is "<<endl;

cout<<buildingProblem(n);

cout<<endl;

return0;

}

Program Explanation

In the main function, we ask the user to input the value for number of buildings. We pass this value to the function buildingProblem as parameter. This function will calculate the expected result and return it. The returned value will be displayed.

advertisement

Runtime Test Cases

Case-1:
$ g++ building_problem.cpp
$ ./a.outEnter the number of plots 3
The number of ways in which buildings can be constructed with the given constraints is
5