计算建造房屋的可能方式


这里给出了 n 个部分,在每个部分中,公路两侧都有两侧可用于建造房屋。如果两幢房屋之间需要留出一块空地,那么在该地块上建造房屋有多少种可能的方式。

建造房屋有四种可能

  •  公路的一侧
  •  公路的另一侧
  •  不能建造任何房屋
  •  公路的两侧

输入和输出

Input:
It takes the number of sections to construct buildings. Say the input is 3.
Output:
Enter Number of sections: 3
Buildings can be constructed in 25 different ways.

算法

constructionWays(n)

输入:有 n 个部分。

输出 −可能的途径数量。

Begin
   if n = 1, then
      return 4
   countEnd := 1
   countEndSpace := 1

   for i := 2 to n, do
      prevCountEnd := countEnd
      prevCountEndSpace := countEndSpace
      countEndSpace := countEnd + prevCountEndSpace
      countEnd := prevCountEndSpace
   done

   answer := countEndSpace + countEnd
   return answer^2
End

示例

#include<iostream>
using namespace std;

int constructionWays(int n) {
   if (n == 1)        //if there is one section
      return 4;       //4 possible ways to construct building in that section

   //set counting values for place at the end and end with space
   int countEnd=1, countEndSpace=1, prevCountEnd, prevCountEndSpace;

   for (int i=2; i<=n; i++) {       //fot the second section to nth section
      prevCountEnd = countEnd;
      prevCountEndSpace = countEndSpace;

      countEndSpace = countEnd + prevCountEndSpace;
      countEnd = prevCountEndSpace;
   }

   //possible ways to end with space and building at the end
   int answer = countEndSpace + countEnd;

   return (answer*answer);     //for two sides the answer will be squared
}

int main() {
   int n;
   cout << "Enter Number of sections: ";
   cin >> n;
   cout << "Buildings can be constructed in " << constructionWays(n) <<" different ways." ;
}

输出

Enter Number of sections: 3
Buildings can be constructed in 25 different ways.

更新于:16-Jun-2020

550 次浏览

提升你的职业

完成课程后获得认证

开始
广告