This is a C++ Program that Solves Building Problem using Dynamic Programming technique.
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.
This is a very simple problem if you observe it carefully. The solution to this problem is simply (n+2)th fibonacci number.
Case-1:
n=1 ways=2 either build here or not
Case-2:
n=2 ways=3 (both empty, only first empty, only second empty)
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>
using namespace 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;
return 0;
}
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.
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
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.
- Practice Computer Science MCQs
- Practice Design & Analysis of Algorithms MCQ
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Computer Science Books