Dadas tres arrays A, B y C, la tarea es encontrar la suma de los valores de todos los tripletes especiales . Un triplete especial se define como un triplete (X, Y, Z) donde la condición:
X ≤ Y y Z ≤ Y siempre se cumplen. El valor de cada triplete (X, Y, Z) viene dado por:
f(X, Y, Z) = (X + Y) * (Y + Z)
Nota : si un triplete no es ‘especial’, f(x, y, z) = 0 para ese triplete en particular.
Ejemplos:
Input : A = {1, 4, 5}, B = {2, 3}, C = {2, 1, 3} Output : 81 Explanation The special triplets and their values are given below Triplet f(x, y, z) = (x + y) * (y + z) (1, 2, 2) (1 + 2) * (2 + 2) = 12 (1, 2, 1) (1 + 2) * (2 + 1) = 9 (1, 3, 2) (1 + 3) * (3 + 2) = 20 (1, 3, 1) (1 + 3) * (3 + 1) = 16 (1, 3, 3) (1 + 3) * (3 + 3) = 24 ------------------------------------- Sum = 81
Método 1 (Fuerza bruta) Generamos todos los tripletes y verificamos si un triplete es un triplete especial, calculamos el valor del triplete usando f(x, y, z) donde (x, y, z) es un triplete especial, y agréguelo a la suma final de todos esos tripletes especiales
C++
// C++ Program to find sum of values of // all special triplets #include <bits/stdc++.h> using namespace std; /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ int findSplTripletsSum(int a[], int b[], int c[], int p, int q, int r) { int sum = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < r; k++) { // (a[i], b[j], c[k]) is special if // a[i] <= b[j] and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value of this special // triplet and add sum of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code int main() { int A[] = { 1, 4, 5 }; int B[] = { 2, 3 }; int C[] = { 2, 1, 3 }; int p = sizeof(A) / sizeof(A[0]); int q = sizeof(B) / sizeof(B[0]); int r = sizeof(C) / sizeof(C[0]); cout << "Sum of values of all special triplets = " << findSplTripletsSum(A, B, C, p, q, r) << endl; }
Java
// Java Program to find sum of values of // all special triplets class GFG { /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ static int findSplTripletsSum(int a[], int b[], int c[], int p, int q, int r) { int sum = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < r; k++) { // (a[i], b[j], c[k]) is special if // a[i] <= b[j] and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value of this special // triplet and add sum of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code public static void main(String[] args) { int A[] = { 1, 4, 5 }; int B[] = { 2, 3 }; int C[] = { 2, 1, 3 }; int p = A.length; int q = B.length; int r = C.length; System.out.print("Sum of values of all special triplets = " + findSplTripletsSum(A, B, C, p, q, r) +"\n"); } } // This code is contributed by 29AjayKumar
Python3
# Python3 Program to find sum of values of # all special triplets # Finding special triplets (x, y, z) where # x belongs to A y belongs to B and z # belongs to C p, q and r are size of # A, B and C respectively def findSplTripletsSum(a, b, c, p, q, r): summ = 0 for i in range(p): for j in range(q): for k in range(r): # (a[i], b[j], c[k]) is special if # a[i] <= b[j] and c[k] <= b[j] if (a[i] <= b[j] and c[k] <= b[j]): # calculate the value of this special # triplet and add sum of all values # of such triplets summ += (a[i] + b[j]) * (b[j] + c[k]) return summ # Driver Code A = [1, 4, 5 ] B = [2, 3 ] C = [2, 1, 3 ] p = len(A) q = len(B) r = len(C) print("Sum of values of all special triplets = ", findSplTripletsSum(A, B, C, p, q, r)) # This code is contributed by Mohit kumar 29
C#
// C# Program to find sum of values of // all special triplets using System; class GFG { /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ static int findSplTripletsSum(int []a, int []b, int []c, int p, int q, int r) { int sum = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < r; k++) { // (a[i], b[j], c[k]) is special if // a[i] <= b[j] and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value of this special // triplet and add sum of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code public static void Main(String[] args) { int []A = { 1, 4, 5 }; int []B = { 2, 3 }; int []C = { 2, 1, 3 }; int p = A.Length; int q = B.Length; int r = C.Length; Console.Write("Sum of values of all special triplets = " + findSplTripletsSum(A, B, C, p, q, r) +"\n"); } } // This code is contributed by PrinciRaj1992
Javascript
<script> // javascript Program to find sum of values of // all special triplets /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ function findSplTripletsSum(a , b , c , p , q , r) { var sum = 0; for (i = 0; i < p; i++) { for (j = 0; j < q; j++) { for (k = 0; k < r; k++) { // (a[i], b[j], c[k]) is special if // a[i] <= b[j] and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value of this special // triplet and add sum of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code var A = [ 1, 4, 5 ]; var B = [ 2, 3 ]; var C = [ 2, 1, 3 ]; var p = A.length; var q = B.length; var r = C.length; document.write("Sum of values of all special triplets = " + findSplTripletsSum(A, B, C, p, q, r) + "\n"); // This code is contributed by todaysgaurav </script>
Sum of values of all special triplets = 81
La Complejidad de Tiempo de este enfoque es O(P * Q * R) donde P, Q y R son los tamaños de las tres arrays A, B y C respectivamente.
Método 2 (eficiente)
Suponga que la
array A contiene elementos {a, b, c, d, e},
la array B contiene elementos {f, g, h, i} y
la array C contiene elementos {j, k, l, m} .
Primero, ordenamos los arreglos A y C para que podamos encontrar la cantidad de elementos en los arreglos A y C que son menores que un B i particular, lo que se puede hacer aplicando una búsqueda binaria en cada valor de B i .
Supongamos que en un índice particular i, el elemento de la array B es B i. Supongamos también que después de que hayamos terminado de ordenar A y C, tenemos elementos {a, b, c} que pertenecen al arreglo A que son menores o iguales que B i y elementos {j, k} que pertenecen al arreglo C, que también es menos que B i .
Lets take Bi = Y from here on. Let, Total Sum of values of all special triplets = S We Know S = Σ f(x, y, z) for all possible (x, y, z) Since elements {a, b, c} of Array A and elements {j, k} of array C are less than Y, the Special Triplets formed consists of triplets formed only using these elements with Y always being the second element of every possible triplet All the Special Triplets and their corresponding values are shown below: Triplet f(x, y, z) = (x + y) * (y + z) (a, Y, j) (a + Y)(Y + j) (a, Y, k) (a + Y)(Y + k) (b, Y, j) (b + Y)(Y + j) (b, Y, k) (b + Y)(Y + k) (c, Y, j) (c + Y)(Y + j) (c, Y, k) (c + Y)(Y + k) The sum of these triplets is S = (a + Y)(Y + j) + (a + Y)(Y + k) + (b + Y)(Y + j) + (b + Y)(Y + k) + (c + Y)(Y + j) + (c + Y)(Y + k) Taking (a + X), (b + X) and (c + x) as common terms we have, S = (a + Y)(Y + j + Y + k) + (b + Y)(Y + j + Y + k) + (c + Y)(Y + j + Y + k) Taking (2Y + j + k) common from every term, S = (a + Y + b + Y + c + Y)(2Y + j + k) ∴ S = (3Y + a + b + c)(2Y + j + k) Thus, S = (N * Y + S1) * (M * Y + S2) where, N = Number of elements in A less than Y, M = Number of elements in C less than Y, S1 = Sum of elements in A less than Y and S2 = Sum of elements in C less than Y
Entonces, para cada elemento en B, podemos encontrar el número de elementos menor que él en las arrays A y C usando la búsqueda binaria y la suma de estos elementos se puede encontrar usando sumas de prefijos
C++
// C++ Program to find sum of values // of all special triplets #include <bits/stdc++.h> using namespace std; /* Utility function for findSplTripletsSum() finds total sum of values of all special triplets */ int findSplTripletsSumUtil(int A[], int B[], int C[], int prefixSumA[], int prefixSumC[], int p, int q, int r) { int totalSum = 0; // Traverse through whole array B for (int i = 0; i < q; i++) { // store current element Bi int currentElement = B[i]; // n = number of elements in A less than current // element int n = upper_bound(A, A + p, currentElement) - A; // m = number of elements in C less than current // element int m = upper_bound(C, C + r, currentElement) - C; // if there are Elements neither in A nor C which // are less than or equal to the current element if (n == 0 || m == 0) continue; /* total sum = (n * currentElement + sum of first n elements in A) + (m * currentElement + sum of first m elements in C) */ totalSum += ((prefixSumA[n - 1] + (n * currentElement)) * (prefixSumC[m - 1] + (m * currentElement))); } return totalSum; } /* Builds prefix sum array for arr of size n and returns a pointer to it */ int* buildPrefixSum(int* arr, int n) { // Dynamically allocate memory tp Prefix Sum Array int* prefixSumArr = new int[n]; // building the prefix sum prefixSumArr[0] = arr[0]; for (int i = 1; i < n; i++) prefixSumArr[i] = prefixSumArr[i - 1] + arr[i]; return prefixSumArr; } /* Wrapper for Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ int findSplTripletsSum(int A[], int B[], int C[], int p, int q, int r) { int specialTripletSum = 0; // sort arrays A and C sort(A, A + p); sort(C, C + r); // build prefix arrays for A and C int* prefixSumA = buildPrefixSum(A, p); int* prefixSumC = buildPrefixSum(C, r); return findSplTripletsSumUtil(A, B, C, prefixSumA, prefixSumC, p, q, r); } // Driver Code int main() { int A[] = { 1, 4, 5 }; int B[] = { 2, 3 }; int C[] = { 2, 1, 3 }; int p = sizeof(A) / sizeof(A[0]); int q = sizeof(B) / sizeof(B[0]); int r = sizeof(C) / sizeof(C[0]); cout << "Sum of values of all special triplets = " << findSplTripletsSum(A, B, C, p, q, r); }
Java
// Java Program to find sum of values of // all special triplets import java.io.*; import java.util.*; public class GFG { /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ static int findSplTripletsSum(int []a, int []b, int []c, int p, int q, int r) { int sum = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < r; k++) { // (a[i], b[j], c[k]) is // special if a[i] <= b[j] // and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value // of this special // triplet and add sum // of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code public static void main(String args[]) { int []A = { 1, 4, 5 }; int []B = { 2, 3 }; int []C = { 2, 1, 3 }; int p = A.length; int q = B.length; int r = C.length; System.out.print("Sum of values of all" + " special triplets = " + findSplTripletsSum(A, B, C, p, q, r)); } } // This code is contributed by Manish Shaw // (manishshaw1)
Python3
# Python3 Program to find sum of values of # all special triplets # Finding special triplets (x, y, z) # where x belongs to A; y belongs to B # and z belongs to C; p, q and r are # size of A, B and C respectively def findSplTripletsSum(a, b, c, p, q, r): sum = 0 for i in range(p): for j in range(q): for k in range(r): # (a[i], b[j], c[k]) is # special if a[i] <= b[j] # and c[k] <= b[j]; if(a[i] <= b[j] and c[k] <= b[j]): # calculate the value # of this special # triplet and add sum # of all values # of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]) return sum # Driver Code A = [1, 4, 5] B = [2, 3 ] C = [2, 1, 3] p = len(A) q = len(B) r = len(C) print("Sum of values of all","special triplets =",findSplTripletsSum(A, B, C, p, q, r)) # This code is contributed by avanitrachhadiya2155
C#
// C# Program to find sum of values of // all special triplets using System; using System.Collections.Generic; using System.Linq; class GFG { /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ static int findSplTripletsSum(int []a, int []b, int []c, int p, int q, int r) { int sum = 0; for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { for (int k = 0; k < r; k++) { // (a[i], b[j], c[k]) is special if // a[i] <= b[j] and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value of this special // triplet and add sum of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code public static void Main() { int []A = { 1, 4, 5 }; int []B = { 2, 3 }; int []C = { 2, 1, 3 }; int p = A.Length; int q = B.Length; int r = C.Length; Console.WriteLine("Sum of values of all special triplets = " + findSplTripletsSum(A, B, C, p, q, r)); } } // This code is contributed by // Manish Shaw (manishshaw1)
Javascript
<script> // Javascript Program to find sum of values of // all special triplets /* Finding special triplets (x, y, z) where x belongs to A; y belongs to B and z belongs to C; p, q and r are size of A, B and C respectively */ function findSplTripletsSum(a,b,c,p,q,r) { let sum = 0; for (let i = 0; i < p; i++) { for (let j = 0; j < q; j++) { for (let k = 0; k < r; k++) { // (a[i], b[j], c[k]) is // special if a[i] <= b[j] // and c[k] <= b[j]; if (a[i] <= b[j] && c[k] <= b[j]) { // calculate the value // of this special // triplet and add sum // of all values // of such triplets sum += (a[i] + b[j]) * (b[j] + c[k]); } } } } return sum; } // Driver Code let A=[1, 4, 5]; let B=[ 2, 3 ]; let C=[2, 1, 3 ]; let p = A.length; let q = B.length; let r = C.length; document.write("Sum of values of all" + " special triplets = " + findSplTripletsSum(A, B, C, p, q, r)); // This code is contributed by patel2127 </script>
Sum of values of all special triplets = 81
Dado que necesitamos iterar a través de toda la array B y para cada elemento aplicar búsquedas binarias en la array A y C, la Complejidad de tiempo de este enfoque es O(Q * (logP + logR)) donde P, Q y R son los tamaños de las tres arrays A, B y C respectivamente.