計算建造房屋的可能方式


這裡給出了 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 次瀏覽

提升你的職業

完成課程後獲得認證

開始
廣告
© . All rights reserved.