C++中给定和的四元组计数
我们给出四个数组。目标是从四个数组中找到元素的四元组,这些元素的和等于给定的 Sum 值。所选元素应满足所有 4 个元素都属于不同的数组。
我们将通过使用 for 循环遍历所有数组并检查 A[i]+B[j]+C[k]+D[l]==sum 来实现这一点。如果是,则递增计数。
让我们通过示例来理解 -
输入 -
A[]={ 1,3,1}, B[]={ 2,4,5 } , C[]={ 1,1,2 } , D[]= { 4,4,0} Sum=5输出 - 给定和的四元组计数为 - 2
说明 -
2 quadrutplets are: (A[0],B[0],C[2],D[2]) → (1,2,2,0), sum=5 (A[2],B[0],C[2],D[2]) → (1,2,2,0), sum=5
输入 -
A[]={ 1,1,1}, B[]={ 1,1,1 } , C[]={ 1,1,1 } , D[]= {1,1,1} Sum=3输出 - 给定和的四元组计数为 - 0
说明 -所有四元组的和将为 4,大于 3。
下面程序中使用的算法如下
我们首先获取整数数组 first[]、second[]、third[] 和 fourth[],它们具有相同的长度并用随机数初始化。
获取变量 first_size、second_size、third_size、fourth_size 分别存储它们的长度。
获取变量 sum 用于存储给定的和值。
函数 quadruplets(int first[], int second[], int third[], int fourth[], int first_size, int second_size, int third_size, int fourth_size, int sum) 获取所有数组及其长度以及和,并返回给定和的四元组计数。
使用 FOR 循环遍历每个数组
最外层循环 0<=i<first_size 用于 first[],然后 0<=j<second_size 用于 second[],0<=k<third_size 用于 third[],以及 0<=l<fourth_size 用于 fourth[]。
比较 first[i] + second[j] + third[k] + fourth[l] == sum。如果为真,则递增计数。
在所有循环结束时,count 将包含给定和的四元组。
返回 count 作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int quadruplets(int first[], int second[], int third[], int fourth[], int first_size, int second_size, int
third_size, int fourth_size, int sum){
int count = 0;
for (int i = 0; i < first_size; i++){
for (int j = 0; j < second_size; j++){
for (int k = 0; k < third_size; k++){
for (int l = 0; l < fourth_size; l++){
if (first[i] + second[j] + third[k] + fourth[l] == sum){
count++;
}
}
}
}
}
return count;
}
int main(){
int first[] = { 7, -8 };
int second[] = { 7, -2 };
int third[] = { 4, -2 };
int fourth[] = { 3, -4 };
int first_size = sizeof(first) / sizeof(first[0]);
int second_size = sizeof(second) / sizeof(second[0]);
int third_size = sizeof(third) / sizeof(third[0]);
int fourth_size = sizeof(fourth) / sizeof(fourth[0]);
int sum= 0;
cout<<"Count of quadruplets with given sum are: "<<quadruplets(first, second, third, fourth, first_size, second_size, third_size, fourth_size, sum);
return 0;
}输出
如果我们运行以上代码,它将生成以下输出 -
Count of quadruplets with given sum are: 1
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP