C++ n条水平平行线与m条垂直平行线相交的平行四边形的数量

C++ n条水平平行线与m条垂直平行线相交的平行四边形的数量(Number of parallelograms when n horizontal parallel lines intersect m vertical parallel lines)

给定两个正整数n和m。任务是计算 n 条水平平行线与 m 条垂直平行线相交可以形成任意大小的平行四边形的数量。

例子:

输入:n = 3, m = 2

输出:3

2个尺寸为 1x1 的平行四边形和 1 个尺寸为 2x1 的平行四边形。

输入:n = 5, m = 5

输出:100

这个想法是使用组合,即从给定的 n 个项目中选择 k 个项目的方式数由n C r,表示如图:给出。

要形成平行四边形,我们需要两条水平平行线和两条垂直平行线。因此,选择两条水平平行线的方式数为n C 2,表示如图:,选择两条垂直平行线的方式数为m C 2,表示如图:。因此,可能的平行四边形总数为n C 2 x m C 2,表示如图:

以下是此方法的实现:

// CPP Program to find number of parallelogram when

// n horizontal parallel lines intersect m vertical

// parallel lines.

#include<bits/stdc++.h>

#define MAX 10

using namespace std;

// Find value of Binomial Coefficient

int binomialCoeff(int C[][MAX], int n, int k)

{

// Calculate value of Binomial Coefficient

// in bottom up manner

for (int i = 0; i <= n; i++)

{

for (int j = 0; j <= min(i, k); j++)

{

// Base Cases

if (j == 0 || j == i)

C[i][j] = 1;

// Calculate value using previously

// stored values

else

C[i][j] = C[i-1][j-1] + C[i-1][j];

}

}

}

// Return number of parallelogram when n horizontal

// parallel lines intersect m vertical parallel lines.

int countParallelogram(int n, int m)

{

int C[MAX][MAX] = { 0 };

binomialCoeff(C, max(n, m), 2);

return C[n][2] * C[m][2];

}

// Driver Program

int main()

{

int n = 5, m = 5;

cout << countParallelogram(n, m) << endl;

return 0;

}

输出:

100

时间复杂度: O(n 2 ) ,如图:

辅助空间: O(n 2 ),如图:

使用基础数学

同样的问题可以通过使用基本数学来解决,因为我们知道n C 2 = n*(n-1)/2, m C 2,表示如图: 也是如此,所以只需使用基本数学,我们就可以在 O(1) 中解决这个问题

以下是上述方法的实现:

#include <iostream>

class GFG {

public:

static int findtheParallelogram(int n, int m)

{

// as nC2 = (n*(n-1))/2

int result

= ((n * (n - 1)) / 2) * ((m * (m - 1)) / 2);

return result;

}

};

int main()

{

int n = 5;

int m = 5;

std::cout << GFG::findtheParallelogram(n, m)

<< std::endl;

return 0;

}

输出:

100

**时间复杂度:**O(1)

**空间复杂度:**O(1)

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
遇见尚硅谷26 分钟前
C语言:20250728学习(指针)
c语言·开发语言·数据结构·c++·笔记·学习·算法
☆璇30 分钟前
【C++】C/C++内存管理
c语言·开发语言·c++
铭哥的编程日记2 小时前
《C++ list 完全指南:从基础到高效使用》
开发语言·c++·list
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 155. 最小栈 (栈)
java·c++·算法·leetcode·面试·go
铭哥的编程日记5 小时前
《C++继承详解:从入门到理解公有、私有与保护继承》
c++
qq_433554545 小时前
C++ 哈希算法、贪心算法
开发语言·c++·哈希算法
CYRUS_STUDIO5 小时前
动态篡改 so 函数返回值:一篇带你玩转 Android Hook 技术!
android·c++·逆向
liulilittle6 小时前
DDD领域驱动中瘦模型与富态模型的核心区别
开发语言·c++·算法·ddd·领域驱动·思想
铭哥的编程日记6 小时前
《C++ string 完全指南:string的模拟实现》
c++
Yu_Lijing6 小时前
MySQL进阶学习与初阶复习第二天
数据库·c++·学习·mysql