El subarreglo más pequeño con GCD como 1 | Árbol de segmentos

Dada una array arr[] , la tarea es encontrar las sub-arrays más pequeñas con GCD igual a 1 . Si no existe tal subarreglo, imprima -1 .

Ejemplos:  

Entrada: arr[] = {2, 6, 3} 
Salida:
{2, 6, 3} es el único subarreglo con GCD = 1.

Entrada: arr[] = {2, 2, 2} 
Salida: -1  

Enfoque: este problema se puede resolver en O (NlogN) utilizando una estructura de datos de árbol de segmentos . El segmento que se construirá se puede usar para responder consultas de rango-gcd.

Entendamos el algoritmo ahora. Utilice la técnica de dos puntos para resolver este problema. Hagamos algunas observaciones antes de discutir el algoritmo. 

  • Digamos que G es el GCD del subarreglo arr[l…r] y G1 es el GCD del subarreglo arr[l+1…r] . G menor o igual a G1 siempre.
  • Digamos que para el L1 dado , R1 es el primer índice tal que GCD del rango [L, R] es 1 que para cualquier L2 mayor o igual que L1 , R2 también será mayor o igual que R1 .

Después de la observación anterior, la técnica de dos punteros tiene mucho sentido, es decir, si se conoce la longitud de la R más pequeña para un índice L y luego para un índice L + 1 , la búsqueda debe comenzar desde R en adelante.

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

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define maxLen 30
 
// Array to store segment-tree
int seg[3 * maxLen];
 
// Function to build segment-tree to
// answer range GCD queries
int build(int l, int r, int in, int* arr)
{
    // Base-case
    if (l == r)
        return seg[in] = arr[l];
 
    // Mid element of the range
    int mid = (l + r) / 2;
 
    // Merging the result of left and right sub-tree
    return seg[in] = __gcd(build(l, mid, 2 * in + 1, arr),
                           build(mid + 1, r, 2 * in + 2, arr));
}
 
// Function to perform range GCD queries
int query(int l, int r, int l1, int r1, int in)
{
    // Base-cases
    if (l1 <= l and r <= r1)
        return seg[in];
    if (l > r1 or r < l1)
        return 0;
 
    // Mid-element
    int mid = (l + r) / 2;
 
    // Calling left and right child
    return __gcd(query(l, mid, l1, r1, 2 * in + 1),
                 query(mid + 1, r, l1, r1, 2 * in + 2));
}
 
// Function to find the required length
int findLen(int* arr, int n)
{
    // Building the segment tree
    build(0, n - 1, 0, arr);
 
    // Two pointer variables
    int i = 0, j = 0;
 
    // To store the final answer
    int ans = INT_MAX;
 
    // Looping
    while (i < n) {
 
        // Incrementing j till we don't get
        // a gcd value of 1
        while (j < n and query(0, n - 1, i, j, 0) != 1)
            j++;
 
        if (j == n)
            break;
 
        // Updating the final answer
        ans = min((j - i + 1), ans);
 
        // Incrementing i
        i++;
 
        // Updating j
        j = max(j, i);
    }
 
    // Returning the final answer
    if (ans == INT_MAX)
        return -1;
    else
        return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 2, 2 };
    int n = sizeof(arr) / sizeof(int);
 
    cout << findLen(arr, n);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
static int maxLen = 30;
 
// Array to store segment-tree
static int []seg = new int[3 * maxLen];
 
// Function to build segment-tree to
// answer range GCD queries
static int build(int l, int r,
                 int in, int[] arr)
{
    // Base-case
    if (l == r)
        return seg[in] = arr[l];
 
    // Mid element of the range
    int mid = (l + r) / 2;
 
    // Merging the result of left and right sub-tree
    return seg[in] = __gcd(build(l, mid, 2 * in + 1, arr),
                           build(mid + 1, r, 2 * in + 2, arr));
}
 
// Function to perform range GCD queries
static int query(int l, int r,
                 int l1, int r1, int in)
{
    // Base-cases
    if (l1 <= l && r <= r1)
        return seg[in];
    if (l > r1 || r < l1)
        return 0;
 
    // Mid-element
    int mid = (l + r) / 2;
 
    // Calling left and right child
    return __gcd(query(l, mid, l1, r1, 2 * in + 1),
                 query(mid + 1, r, l1, r1, 2 * in + 2));
}
 
// Function to find the required length
static int findLen(int []arr, int n)
{
    // Building the segment tree
    build(0, n - 1, 0, arr);
 
    // Two pointer variables
    int i = 0, j = 0;
 
    // To store the final answer
    int ans = Integer.MAX_VALUE;
 
    // Looping
    while (i < n)
    {
 
        // Incrementing j till we don't get
        // a gcd value of 1
        while (j < n && query(0, n - 1,
                              i, j, 0) != 1)
            j++;
 
        if (j == n)
            break;
 
        // Updating the final answer
        ans = Math.min((j - i + 1), ans);
 
        // Incrementing i
        i++;
 
        // Updating j
        j = Math.max(j, i);
    }
 
    // Returning the final answer
    if (ans == Integer.MAX_VALUE)
        return -1;
    else
        return ans;
}
 
static int __gcd(int a, int b)
{
    return b == 0 ? a : __gcd(b, a % b);    
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 2, 2, 2 };
    int n = arr.length;
 
    System.out.println(findLen(arr, n));
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
from math import gcd as __gcd
 
maxLen = 30
 
# Array to store segment-tree
seg = [0 for i in range(3 * maxLen)]
 
# Function to build segment-tree to
# answer range GCD queries
def build(l, r, inn, arr):
     
    # Base-case
    if (l == r):
        seg[inn] = arr[l]
        return seg[inn]
 
    # Mid element of the range
    mid = (l + r) // 2
 
    # Merging the result of
    # left and right sub-tree
    seg[inn] = __gcd(build(l, mid,
                           2 * inn + 1, arr),
                     build(mid + 1, r,
                           2 * inn + 2, arr))
 
    return seg[inn]
 
# Function to perform range GCD queries
def query(l, r, l1, r1, inn):
     
    # Base-cases
    if (l1 <= l and r <= r1):
        return seg[inn]
    if (l > r1 or r < l1):
        return 0
 
    # Mid-element
    mid = (l + r) // 2
 
    # Calling left and right child
    x=__gcd(query(l, mid, l1, r1,
                  2 * inn + 1),
            query(mid + 1, r, l1, r1,
                  2 * inn + 2))
    return x
 
# Function to find the required length
def findLen(arr, n):
     
    # Building the segment tree
    build(0, n - 1, 0, arr)
 
    # Two pointer variables
    i = 0
    j = 0
 
    # To store the final answer
    ans = 10**9
 
    # Loopinng
    while (i < n):
 
        # Incrementing j till we
        # don't get a gcd value of 1
        while (j < n and query(0, n - 1,
                               i, j, 0) != 1):
            j += 1
 
        if (j == n):
            break;
 
        # Updating the final answer
        ans = minn((j - i + 1), ans)
 
        # Incrementing i
        i += 1
 
        # Updating j
        j = max(j, i)
 
    # Returning the final answer
    if (ans == 10**9):
        return -1
    else:
        return ans
 
# Driver code
arr = [2, 2, 2]
n = len(arr)
 
print(findLen(arr, n))
 
# This code is contributed by Mohit Kumar

C#

// C# implementation of the approach
using System;
 
class GFG
{
    static int maxLen = 30;
     
    // Array to store segment-tree
    static int []seg = new int[3 * maxLen];
     
    // Function to build segment-tree to
    // answer range GCD queries
    static int build(int l, int r,
                     int ind, int[] arr)
    {
        // Base-case
        if (l == r)
            return seg[ind] = arr[l];
     
        // Mid element of the range
        int mid = (l + r) / 2;
     
        // Merging the result of left and right sub-tree
        return seg[ind] = __gcd(build(l, mid, 2 * ind + 1, arr),
                                build(mid + 1, r, 2 * ind + 2, arr));
    }
     
    // Function to perform range GCD queries
    static int query(int l, int r,
                     int l1, int r1, int ind)
    {
        // Base-cases
        if (l1 <= l && r <= r1)
            return seg[ind];
        if (l > r1 || r < l1)
            return 0;
     
        // Mid-element
        int mid = (l + r) / 2;
     
        // Calling left and right child
        return __gcd(query(l, mid, l1, r1, 2 * ind + 1),
                     query(mid + 1, r, l1, r1, 2 * ind + 2));
    }
     
    // Function to find the required length
    static int findLen(int []arr, int n)
    {
        // Building the segment tree
        build(0, n - 1, 0, arr);
     
        // Two pointer variables
        int i = 0, j = 0;
     
        // To store the final answer
        int ans = int.MaxValue;
     
        // Looping
        while (i < n)
        {
     
            // Incrementing j till we don't get
            // a gcd value of 1
            while (j < n && query(0, n - 1,
                                  i, j, 0) != 1)
                j++;
     
            if (j == n)
                break;
     
            // Updating the final answer
            ans = Math.Min((j - i + 1), ans);
     
            // Incrementing i
            i++;
     
            // Updating j
            j = Math.Max(j, i);
        }
     
        // Returning the final answer
        if (ans == int.MaxValue)
            return -1;
        else
            return ans;
    }
     
    static int __gcd(int a, int b)
    {
        return b == 0 ? a : __gcd(b, a % b);    
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = { 2, 2, 2 };
        int n = arr.Length;
     
        Console.WriteLine(findLen(arr, n));
    }
}
 
// This code is contributed by kanugargng

Javascript

<script>
// Javascript implementation of the approach
 
let maxLen = 30;
// Array to store segment-tree
let seg = new Array(3 * maxLen);
 
// Function to build segment-tree to
// answer range GCD queries
function build(l,r,In,arr)
{
    // Base-case
    if (l == r)
        return seg[In] = arr[l];
   
    // Mid element of the range
    let mid = Math.floor((l + r) / 2);
   
    // Merging the result of left and right sub-tree
    return seg[In] = __gcd(build(l, mid, 2 * In + 1, arr),
                           build(mid + 1, r, 2 * In + 2, arr));
}
 
// Function to perform range GCD queries
function query(l,r,l1,r1,In)
{
    // Base-cases
    if (l1 <= l && r <= r1)
        return seg[In];
    if (l > r1 || r < l1)
        return 0;
   
    // Mid-element
    let mid = Math.floor((l + r) / 2);
   
    // Calling left and right child
    return __gcd(query(l, mid, l1, r1, 2 * In + 1),
                 query(mid + 1, r, l1, r1, 2 * In + 2));
}
 
// Function to find the required length
function findLen(arr,n)
{
    // Building the segment tree
    build(0, n - 1, 0, arr);
   
    // Two pointer variables
    let i = 0, j = 0;
   
    // To store the final answer
    let ans = Number.MAX_VALUE;
   
    // Looping
    while (i < n)
    {
   
        // Incrementing j till we don't get
        // a gcd value of 1
        while (j < n && query(0, n - 1,
                              i, j, 0) != 1)
            j++;
   
        if (j == n)
            break;
   
        // Updating the final answer
        ans = Math.min((j - i + 1), ans);
   
        // Incrementing i
        i++;
   
        // Updating j
        j = Math.max(j, i);
    }
   
    // Returning the final answer
    if (ans == Number.MAX_VALUE)
        return -1;
    else
        return ans;
}
 
function __gcd(a,b)
{
    return b == 0 ? a : __gcd(b, a % b);    
}
 
// Driver code
let arr=[2, 2, 2 ];
let n = arr.length;
document.write(findLen(arr, n));
 
 
 
// This code is contributed by unknown2108
</script>
Producción: 

-1

 

Publicación traducida automáticamente

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