📌  相关文章
📜  具有子数组乘积的最小索引对与左边或右边的子数组乘积互质

📅  最后修改于: 2021-04-23 08:02:16             🧑  作者: Mango

给定长度为N的数组arr [] ,任务是找到最小的索引对(i,j) ,以使子数组arr [i + 1,j – 1]中元素的乘积与任意一个互素数子数组arr [0,i]或子数组arr [j,N]的乘积。如果不存在这样的对,则打印“ -1”

例子:

天真的方法:最简单的方法是遍历每对可能的索引(i,j) ,对于每对索引,找到子数组arr [0,i]arr [j,N]的乘积,并检查它是否为co-是否使用子数组arr [i + 1,j – 1]的乘积来素数。如果发现是正确的,则打印那些索引对。如果不存在这样的对,则打印“ -1”

时间复杂度: O((N 3 )* log(M)),其中M是数组所有元素的乘积。
辅助空间: O(1)

高效方法:为了优化上述方法,其思想是使用辅助数组存储数组元素的后缀乘积。请按照以下步骤解决问题:

  • 将后缀元素的乘积存储在rightProd []中,其中rightProd [i]存储来自arr [i],arr [N – 1]的元素乘积。
  • 查找数组中所有元素的乘积作为totalProd。
  • 使用变量i遍历给定数组并执行以下操作:
    • 初始化一个变量,例如product
    • 使用[i,N – 1]范围内的变量j遍历数组。
    • 通过ARR [J]乘以产品换代产品
    • leftProduct初始化为total / right_prod [i]
    • 检查产品是否与leftProductrightProduct之一底涂。如果发现是正确的,则打印该对(i – 1,j + 1)并退出循环。
  • 完成上述步骤后,如果不存在这样的一对,则打印“ -1”

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate GCD
// of two integers
int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
void findPair(int A[], int N)
{
    // Stores the suffix product
    // of array elements
    int right_prod[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for (int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1]
                        * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for (int i = 1; i < N - 1; i++) {
 
        product = 1;
        for (int j = i; j < N - 1; j++) {
 
            // Store product of A[i, j]
            product *= A[j];
 
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product,
                    right_prod[j + 1])
                    == 1
                || gcd(product,
                       total_prod
                           / right_prod[i])
                       == 1) {
 
                flag = 1;
                cout << "(" << i - 1
                     << ", " << j + 1
                     << ")";
                break;
            }
        }
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        cout << -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 1, 3, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findPair(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to calculate GCD
// of two integers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
static void findPair(int A[], int N)
{
     
    // Stores the suffix product
    // of array elements
    int right_prod[] = new int[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for(int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1] * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for(int i = 1; i < N - 1; i++)
    {
        product = 1;
        for(int j = i; j < N - 1; j++)
        {
             
            // Store product of A[i, j]
            product *= A[j];
 
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 ||
                gcd(product, total_prod /
                    right_prod[i]) == 1)
            {
                flag = 1;
                System.out.println("(" + (i - 1) + ", " +
                                         (j + 1) + ")");
                break;
            }
        }
         
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        System.out.print(-1);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 4, 1, 3, 7 };
    int N = arr.length;
 
    // Function Call
    findPair(arr, N);
}
}
 
// This code is contributed by chitranayal


Python3
# Python3 program for the above approach
 
# Function to calculate GCD
# of two integers
def gcd(a, b):
     
    if (b == 0):
        return a
 
    # Recursively calculate GCD
    return gcd(b, a % b)
 
# Function to find the lexicographically
# smallest pair of indices whose product
# is co-prime with the product of the
# subarrays on its left and right
def findPair(A, N):
     
    # Stores the suffix product
    # of array elements
    right_prod = [0] * N
 
    # Set 0/1 if pair satisfies the
    # given condition or not
    flag = 0
     
    # Initialize array right_prod
    right_prod[N - 1] = A[N - 1]
 
    # Update the suffix product
    for i in range(N - 2, 0, -1):
        right_prod[i] = right_prod[i + 1] * A[i]
 
    # Stores product of all elements
    total_prod = right_prod[0]
 
    # Stores the product of subarray
    # in between the pair of indices
    product = 1
 
    # Iterate through every pair of
    # indices (i, j)
    for i in range(1, N - 1):
        product = 1
        for j in range(i, N - 1):
             
            # Store product of A[i, j]
            product *= A[j]
             
            # Check if product is co-prime
            # to product of either the left
            # or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 or
                gcd(product, total_prod /
                             right_prod[i]) == 1):
                flag = 1
                print("(" , (i - 1) , ", " ,
                            (j + 1) ,")")
                break
 
        if (flag == 1):
            break
 
    # If no such pair is found,
    # then pr-1
    if (flag == 0):
        print(-1)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 4, 1, 3, 7 ]
    N = len(arr)
 
    # Function Call
    findPair(arr, N)
 
# This code is contributed by Amit Katiyar


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate GCD
// of two integers
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
 
    // Recursively calculate GCD
    return gcd(b, a % b);
}
 
// Function to find the lexicographically
// smallest pair of indices whose product
// is co-prime with the product of the
// subarrays on its left and right
static void findPair(int []A, int N)
{
     
    // Stores the suffix product
    // of array elements
    int []right_prod = new int[N];
 
    // Set 0/1 if pair satisfies the
    // given condition or not
    int flag = 0;
 
    // Initialize array right_prod[]
    right_prod[N - 1] = A[N - 1];
 
    // Update the suffix product
    for(int i = N - 2; i >= 0; i--)
        right_prod[i] = right_prod[i + 1] * A[i];
 
    // Stores product of all elements
    int total_prod = right_prod[0];
 
    // Stores the product of subarray
    // in between the pair of indices
    int product;
 
    // Iterate through every pair of
    // indices (i, j)
    for(int i = 1; i < N - 1; i++)
    {
        product = 1;
         
        for(int j = i; j < N - 1; j++)
        {
             
            // Store product of A[i, j]
            product *= A[j];
             
            // Check if product is co-prime
            // to product of either the left
            // or right subarrays
            if (gcd(product, right_prod[j + 1]) == 1 ||
                gcd(product, total_prod /
                    right_prod[i]) == 1)
            {
                flag = 1;
                Console.WriteLine("(" + (i - 1) + ", " +
                                        (j + 1) + ")");
                break;
            }
        }
         
        if (flag == 1)
            break;
    }
 
    // If no such pair is found,
    // then print -1
    if (flag == 0)
        Console.Write(-1);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 2, 4, 1, 3, 7 };
    int N = arr.Length;
     
    // Function Call
    findPair(arr, N);
}
}
 
// This code is contributed by Princi Singh


输出:
(0, 2)

时间复杂度: O(N 2 * log(M)),其中M是数组中所有元素的乘积
辅助空间: O(N)