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.
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Computer Science Books
- Buy Data Structure Books
- Apply for Information Technology Internship
- Apply for Data Structure Internship
- Practice Computer Science MCQs