Encuentre m-ésimo valor más pequeño en k arrays ordenadas

Dado k arreglos ordenados de tamaños posiblemente diferentes, encuentre el m-ésimo valor más pequeño en el arreglo fusionado.
Ejemplos: 
 

Input: m = 5     
      arr[][] = { {1, 3},
                  {2, 4, 6},
                  {0, 9, 10, 11}} ;
Output: 4
Explanation The merged array would
be {0 1 2 3 4 6 9 10 11}.  The 5-th 
smallest element in this merged
array is 4.

Input: m = 2
      arr[][] = { {1, 3, 20},
                  {2, 4, 6}} ;
Explanation The merged array would
be {1 2 3 4 6 20}. The 2nd smallest element would be 2. 
Output: 2

Una solución simple es crear una array de salida y, una por una, copiar todas las arrays en ella. Finalmente, ordene la array de salida usando. Este enfoque toma el tiempo O(N Logn N) donde N es el conteo de todos los elementos.
Una solución eficiente es utilizar la estructura de datos del montón. La complejidad temporal de la solución basada en almacenamiento dinámico es O(m Log k).
1. Cree un montón mínimo de tamaño k e inserte el primer elemento en todas las arrays en el montón 
2. Repita los siguientes pasos m veces 
… a) Elimine el elemento mínimo del montón (el mínimo siempre está en la raíz) y guárdelo en la array de salida . 
…..b) Insertar el siguiente elemento de la array de la que se extrae el elemento. Si la array no tiene más elementos, no haga nada. 
3. Imprima el último elemento eliminado.
 

CPP

// C++ program to find m-th smallest element
// in the merged arrays.
#include <bits/stdc++.h>
using namespace std;
 
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array.
typedef pair<int, pair<int, int> > ppi;
 
// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It returns m-th smallest element in
// the array obtained after merging the given
// arrays.
int mThLargest(vector<vector<int> > arr, int m)
{
    // Create a min heap with k heap nodes. Every
    // heap node has first element of an array
    priority_queue<ppi, vector<ppi>, greater<ppi> > pq;
 
    for (int i = 0; i < arr.size(); i++)
        pq.push({ arr[i][0], { i, 0 } });
 
    // Now one by one get the minimum element
    // from min heap and replace it with next
    // element of its array
    int count = 0;
    int i = 0, j = 0;
    while (count < m && pq.empty() == false) {
        ppi curr = pq.top();
        pq.pop();
 
        // i ==> Array Number
        // j ==> Index in the array number
        i = curr.second.first;
        j = curr.second.second;
 
        // The next element belongs to same array as
        // current.
        if (j + 1 < arr[i].size())
            pq.push({ arr[i][j + 1], { i, j + 1 } });
 
        count++;
    }
 
    return arr[i][j];
}
 
// Driver program to test above functions
int main()
{
    vector<vector<int> > arr{ { 2, 6, 12 },
                              { 1, 9 },
                              { 23, 34, 90, 2000 } };
 
    int m = 4;
    cout << mThLargest(arr, m);
 
    return 0;
}
Producción: 

9

 

Publicación traducida automáticamente

Artículo escrito por kartik 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 *