Cuente tripletes no equidistantes de distintos elementos de array que tienen índices en orden creciente

Dada una array arr[] de tamaño N que consta de solo 0 s, 1 s y 2 s, la tarea es encontrar el recuento de tripletes de índices (i, j, k) que contienen distintos elementos de array tales que i < j < k y los elementos del arreglo no son equidistantes, es decir, (j – i )!= (k – j) .

Ejemplos:

Entrada: arr[] = { 0, 1, 2, 1 } 
Salida:
Explicación: 
Solo el triplete (0, 2, 3) contiene elementos de array distintos y (2 – 0) != (3 – 2). 
Por lo tanto, la salida requerida es 1.

Entrada: arr[] = { 0, 1, 2 } 
Salida:
Explicación: 
No existe ningún triplete que satisfaga la condición. 
Por lo tanto, la salida requerida es 0.

Enfoque: La idea es almacenar los índices de los elementos del arreglo 0 s, 1 s y 2 s en tres arreglos separados, luego encontrar los tripletes de conteo que satisfacen las condiciones dadas. Siga los pasos a continuación para resolver el problema:

  • Inicialice dos arrays, digamos zero_i[] y one_i[] , para almacenar los índices de 0 s y 1 s de la array dada, respectivamente.
  • Inicialice un mapa, digamos mp , para almacenar los índices de 2 s de la array dada.
  • Encuentre el recuento total de todos los tripletes posibles multiplicando el tamaño de zero_i[] , one_i[] y mp .
  • Ahora, reste todos los tripletes que violen las condiciones dadas.
  • Para encontrar dichos tripletes, recorra las arrays zero_i[] y one_i[] e intente encontrar un tercer índice en el Mapa que viole la condición.
  • Para encontrar el tercer índice que viola las condiciones, se presentan los siguientes tres casos: 
    1. El tercer índice es equidistante de ambos índices y está presente entre ellos.
    2. El tercer índice es equidistante de ambos índices y está presente en el lado izquierdo del primer índice.
    3. El tercer índice es equidistante de ambos índices y está presente en el lado derecho del segundo índice.
  • Retire todos esos tripletes de la cuenta del número total de tripletes.
  • Finalmente, imprima el conteo total de tripletes obtenidos.

A continuación se muestra la implementación del enfoque anterior:

C++14

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
int countTriplets(int* arr, int N)
{
 
    // Stores indices of 0s
    vector<int> zero_i;
 
    // Stores indices of 1s
    vector<int> one_i;
 
    // Stores indices of 2s
    unordered_map<int, int> mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.push_back(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.push_back(i + 1);
 
        // If current array element
        // is 2
        else
            mp[i + 1] = 1;
    }
 
    // Total count of triplets
    int total = zero_i.size()
                * one_i.size() * mp.size();
 
    // Traverse  the array zero_i[]
    for (int i = 0; i < zero_i.size();
         i++) {
 
        // Traverse the array one_i[]
        for (int j = 0; j < one_i.size();
             j++) {
 
            // Stores index of 0s
            int p = zero_i[i];
 
            // Stores index of 1s
            int q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp[r] > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp[r] > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp[r] > 0 && abs(r - p) == abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    cout << total;
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 2, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countTriplets(arr, N);
 
    return 0;
}

Java

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
static void countTriplets(int []arr, int N)
{
     
    // Stores indices of 0s
    Vector<Integer> zero_i = new Vector<Integer>();
 
    // Stores indices of 1s
    Vector<Integer> one_i = new Vector<Integer>();
 
    // Stores indices of 2s
    HashMap<Integer,
            Integer> mp = new HashMap<Integer,
                                      Integer>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.add(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.add(i + 1);
 
        // If current array element
        // is 2
        else
            mp.put(i + 1, 1);
    }
 
    // Total count of triplets
    int total = zero_i.size() *
                 one_i.size() * mp.size();
 
    // Traverse  the array zero_i[]
    for(int i = 0; i < zero_i.size(); i++)
    {
         
        // Traverse the array one_i[]
        for(int j = 0; j < one_i.size(); j++)
        {
             
            // Stores index of 0s
            int p = zero_i.get(i);
 
            // Stores index of 1s
            int q = one_i.get(j);
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.containsKey(r) && mp.get(r) > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.containsKey(r) && mp.get(r) > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.containsKey(r) &&
                    mp.get(r) > 0 &&
                  Math.abs(r - p) == Math.abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    System.out.print(total);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 0, 1, 2, 1 };
    int N = arr.length;
 
    countTriplets(arr, N);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program to implement
# the above approach
 
# Function to find the total count of
# triplets (i, j, k) such that i < j < k
# and (j - i) != (k - j)
def countTriplets(arr, N):
 
    # Stores indices of 0s
    zero_i = []
 
    # Stores indices of 1s
    one_i = []
 
    # Stores indices of 2s
    mp = {}
 
    # Traverse the array
    for i in range(N):
 
        # If current array element
        # is 0
        if (arr[i] == 0):
            zero_i.append(i + 1)
 
        # If current array element is 1
        elif (arr[i] == 1):
            one_i.append(i + 1)
 
        # If current array element
        # is 2
        else:
            mp[i + 1] = 1
 
    # Total count of triplets
    total = len(zero_i) * len(one_i) * len(mp)
 
    # Traverse  the array zero_i[]
    for i in range(len(zero_i)):
 
        # Traverse the array one_i[]
        for j in range(len(one_i)):
 
            # Stores index of 0s
            p = zero_i[i]
 
            # Stores index of 1s
            q = one_i[j]
 
            # Stores third element of
            # triplets that does not
            # satisfy the condition
            r = 2 * p - q
 
            # If r present
            # in the map
            if (r in mp):
                total -= 1
 
            # Update r
            r = 2 * q - p
 
            # If r present
            # in the map
            if (r in mp):
                total -= 1
 
            # Update r
            r = (p + q) // 2
 
            # If r present in the map
            # and equidistant
            if ((r in mp) and abs(r - p) == abs(r - q)):
                total -= 1
 
    # Print the obtained count
    print (total)
 
# Driver Code
if __name__ == '__main__':
    arr = [0, 1, 2, 1]
    N = len(arr)
    countTriplets(arr, N)
 
    # This code is contributed by mohit kumar 29

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
static void countTriplets(int []arr, int N)
{
     
    // Stores indices of 0s
    List<int> zero_i = new List<int>();
 
    // Stores indices of 1s
    List<int> one_i = new List<int>();
 
    // Stores indices of 2s
    Dictionary<int,
            int> mp = new Dictionary<int,
                                      int>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.Add(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.Add(i + 1);
 
        // If current array element
        // is 2
        else
            mp.Add(i + 1, 1);
    }
 
    // Total count of triplets
    int total = zero_i.Count *
                 one_i.Count * mp.Count;
 
    // Traverse  the array zero_i[]
    for(int i = 0; i < zero_i.Count; i++)
    {
         
        // Traverse the array one_i[]
        for(int j = 0; j < one_i.Count; j++)
        {
             
            // Stores index of 0s
            int p = zero_i[i];
 
            // Stores index of 1s
            int q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.ContainsKey(r) && mp[r] > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.ContainsKey(r) && mp[r] > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.ContainsKey(r) &&
                    mp[r] > 0 &&
                  Math.Abs(r - p) == Math.Abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    Console.Write(total);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 0, 1, 2, 1 };
    int N = arr.Length;
    countTriplets(arr, N);
}
}
 
// This code contributed by shikhasingrajput

Javascript

<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
function countTriplets(arr, N)
{
 
    // Stores indices of 0s
    var zero_i = [];
 
    // Stores indices of 1s
    var one_i = [];
 
    // Stores indices of 2s
    var mp = new Map();
 
    // Traverse the array
    for (var i = 0; i < N; i++) {
 
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.push(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.push(i + 1);
 
        // If current array element
        // is 2
        else
            mp.set(i + 1, 1);
    }
 
    // Total count of triplets
    var total = zero_i.length
                * one_i.length * mp.size;
 
    // Traverse  the array zero_i[]
    for (var i = 0; i < zero_i.length;
         i++) {
 
        // Traverse the array one_i[]
        for (var j = 0; j < one_i.length;
             j++) {
 
            // Stores index of 0s
            var p = zero_i[i];
 
            // Stores index of 1s
            var q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            var r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.has(r))
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.has(r))
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.has(r) && Math.abs(r - p) == Math.abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    document.write( total);
}
 
// Driver Code
var arr = [0, 1, 2, 1];
var N = arr.length;
countTriplets(arr, N);
 
 
</script>
Producción: 

1

 

Complejidad de Tiempo: O(N 2 )
Espacio Auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por PratikLath y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *