计算建造建筑物的方法
此处给出了 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.
广告