📌  相关文章
📜  其乘积为两个整数的平方差的子序列数

📅  最后修改于: 2021-05-04 15:05:54             🧑  作者: Mango

给定一个数组arr [],其中包含N个元素,其中N个元素同时包含正负元素,则任务是查找连续子序列的总数,这些子序列的乘积可以表示为两个整数的平方之差。

例子:

天真的方法:这个问题的天真的方法是生成所有连续的子序列并计算其乘积,然后简单地检查该数字是否可以表示为两个平方的差。

下面是上述方法的实现:

C++
// C++ implementation to count the
// number of contiguous subsequences
// whose product can be expressed as
// the square of difference of two integers
 
#include 
using namespace std;
 
// Function to count the number
// of contiguous subsequences
// whose product can be expressed
// as square of difference of two integers
int CntcontSubs(int a[], int n)
{
    int c = 0, d = 0, i, sum = 1, j;
 
    // Iterating through the array
    for (i = 0; i < n; i++) {
 
        // Check if that number can be
        // expressed as the square of
        // difference of two numbers
        if (a[i] % 2 != 0 || a[i] % 4 == 0)
            d++;
 
        // Variable to compute the product
        sum = a[i];
 
        // Finding the remaining subsequences
        for (j = i + 1; j < n; j++) {
            sum = sum * a[j];
 
            // Check if that number can be
            // expressed as the square of
            // difference of two numbers
            if (sum % 2 != 0 || sum % 4 == 0)
                c++;
        }
        sum = 1;
    }
 
    // Return the number of subsequences
    return c + d;
}
 
// Driver code
int main()
{
    int arr[] = { 5, 4, 2, 9, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << CntcontSubs(arr, n);
 
    return 0;
}


Java
// Java implementation to count the
// number of contiguous subsequences
// whose product can be expressed as
// the square of difference of two integers
 
class GFG{
  
// Function to count the number
// of contiguous subsequences
// whose product can be expressed
// as square of difference of two integers
static int CntcontSubs(int a[], int n)
{
    int c = 0, d = 0, i, sum = 1, j;
  
    // Iterating through the array
    for (i = 0; i < n; i++) {
  
        // Check if that number can be
        // expressed as the square of
        // difference of two numbers
        if (a[i] % 2 != 0 || a[i] % 4 == 0)
            d++;
  
        // Variable to compute the product
        sum = a[i];
  
        // Finding the remaining subsequences
        for (j = i + 1; j < n; j++) {
            sum = sum * a[j];
  
            // Check if that number can be
            // expressed as the square of
            // difference of two numbers
            if (sum % 2 != 0 || sum % 4 == 0)
                c++;
        }
        sum = 1;
    }
  
    // Return the number of subsequences
    return c + d;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 5, 4, 2, 9, 8 };
    int n = arr.length;
  
    System.out.print(CntcontSubs(arr, n));
  
}
}
 
// This code contributed by PrinciRaj1992


Python3
# Python3 implementation to count the
# number of contiguous subsequences
# whose product can be expressed as
# the square of difference of two integers
 
# Function to count the number
# of contiguous subsequences
# whose product can be expressed
# as square of difference of two integers
def CntcontSubs(a, n):
    c = 0
    d = 0
    sum = 1
 
    # Iterating through the array
    for i in range(n):
 
        # Check if that number can be
        # expressed as the square of
        # difference of two numbers
        if (a[i] % 2 != 0 or a[i] % 4 == 0):
            d += 1
 
        # Variable to compute the product
        sum = a[i]
 
        # Finding the remaining subsequences
        for j in range(i + 1, n):
            sum = sum * a[j]
 
            # Check if that number can be
            # expressed as the square of
            # difference of two numbers
            if (sum % 2 != 0 or sum % 4 == 0):
                c += 1
        sum = 1
 
    # Return the number of subsequences
    return c + d
 
# Driver code
if __name__ == '__main__':
    arr=[5, 4, 2, 9, 8]
    n = len(arr)
 
    print(CntcontSubs(arr, n))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation to count the
// number of contiguous subsequences
// whose product can be expressed as
// the square of difference of two integers
using System;
 
class GFG{
 
// Function to count the number
// of contiguous subsequences
// whose product can be expressed
// as square of difference of two integers
static int CntcontSubs(int []a, int n)
{
    int c = 0, d = 0, i, sum = 1, j;
 
    // Iterating through the array
    for(i = 0; i < n; i++)
    {
         
       // Check if that number can be
       // expressed as the square of
       // difference of two numbers
       if (a[i] % 2 != 0 || a[i] % 4 == 0)
           d++;
            
       // Variable to compute the product
       sum = a[i];
        
       // Finding the remaining subsequences
       for(j = i + 1; j < n; j++)
       {
          sum = sum * a[j];
           
          // Check if that number can be
          // expressed as the square of
          // difference of two numbers
          if (sum % 2 != 0 || sum % 4 == 0)
              c++;
       }
       sum = 1;
    }
 
    // Return the number of subsequences
    return c + d;
}
 
// Driver code
static void Main()
{
    int []arr = { 5, 4, 2, 9, 8 };
    int n = arr.Length;
     
    Console.Write(CntcontSubs(arr, n));
}
}
 
// This code is contributed by grand_master


Javascript


C++
// C++ implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
 
#include 
using namespace std;
 
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
int CntcontSubs(int a[], int n)
{
    int prod = 1;
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    vector > vect;
 
    vect.push_back(make_pair(0, 2));
 
    vector two, zero;
 
    // Iterating through the array
    for (int i = 0; i < n; i++) {
 
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.push_back(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.push_back(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.push_back(make_pair(i + 1, a[i]));
    }
    vect.push_back(make_pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.empty())
        return total;
    else {
        int sum = 0;
 
        int pos1 = -1, pos2 = -1, pos3 = -1;
 
        int sz = vect.size();
 
        // Iterating through the vector
        for (int i = 1; i + 1 < sz; i++) {
 
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect[i].second == 2) {
                sum += (vect[i].first
                        - vect[i - 1].first)
                           * (vect[i + 1].first
                              - vect[i].first)
                       - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.size();
    }
}
 
// Driver code
int main()
{
    int a[] = { 5, 4, 2, 9, 8 };
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << CntcontSubs(a, n);
 
    return 0;
}


Java
// Java implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
import java.util.*;
class GFG{
static class pair
{
      int first, second;
    public pair(int first, int second) 
    {
          this.first = first;
        this.second = second;
    }   
}
   
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
static int CntcontSubs(int a[], int n)
{
    int prod = 1;
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    Vector vect = new Vector();
 
    vect.add(new pair(0, 2));
    Vector two = new  Vector();
    Vector zero = new  Vector();
 
    // Iterating through the array
    for (int i = 0; i < n; i++)
    {
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.add(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.add(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.add(new pair(i + 1, a[i]));
    }
    vect.add(new pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.isEmpty())
        return total;
    else
    {
        int sum = 0;
        int pos1 = -1, pos2 = -1, pos3 = -1;
        int sz = vect.size();
 
        // Iterating through the vector
        for (int i = 1; i + 1 < sz; i++)
        {
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect.get(i).second == 2)
            {
                sum += (vect.get(i).first -
                        vect.get(i-1).first) *
                       (vect.get(i+1).first -
                        vect.get(i).first) - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.size();
    }
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = {5, 4, 2, 9, 8};
    int n = a.length;
    System.out.print(CntcontSubs(a, n));
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 implementation to count all the
# contiguous subsequences whose product is
# expressed as the square of the difference
# of two integers
 
# Function to count all the
# contiguous subsequences whose
# product is expressed as the square
# of the difference of two integers
def CntcontSubs(a, n):
     
    prod = 1
 
    # Creating vectors to store
    # the remainders and the
    # subsequences
    vect = []
 
    vect.append((0, 2))
 
    two, zero = [], []
 
    # Iterating through the array
    for i in range(n):
         
        # Finding the remainder when the
        # element is divided by 4
        a[i] = a[i] % 4
 
        # Bringing all the elements in
        # the range [0, 3]
        if (a[i] < 0):
            a[i] = a[i] + 4
 
        # If the remainder is 2, store
        # the index of the
        if (a[i] == 2):
            two.append(i + 1)
 
        # If the remainder is 2, store
        # the index of the
        if (a[i] == 0):
            zero.append(i + 1)
 
        if (a[i] == 0 or a[i] == 2):
            vect.append((i + 1, a[i]))
     
    vect.append((n + 1, 2))
 
    # Finding the total number of subsequences
    total = (n * (n + 1)) // 2
 
    # If there are no numbers which
    # yield the remainder 2
    if (len(two) == 0):
        return total
    else:
        Sum = 0
 
        pos1, pos2, pos3 = -1, -1, -1
 
        sz = len(vect)
 
        # Iterating through the vector
        for i in range(1, sz - 1):
             
            # If the element is 2, find the
            # nearest 2 or 0 and find the
            # number of elements between them
            if (vect[i][1] == 2) :
                Sum += ((vect[i][0] - vect[i - 1][0]) *
                        (vect[i + 1][0] - vect[i][0]) - 1)
 
        # Returning the count
        return (total - Sum - len(two))
 
# Driver Code
a = [ 5, 4, 2, 9, 8 ]
n = len(a)
 
print(CntcontSubs(a, n))
 
# This code is contributed by divyeshrabadiya07


C#
// C# implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
using System;
using System.Collections.Generic;
 
class GFG{
     
class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
static int CntcontSubs(int []a, int n)
{
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    List vect = new List();
 
    vect.Add(new pair(0, 2));
    List two = new List();
    List zero = new List();
 
    // Iterating through the array
    for(int i = 0; i < n; i++)
    {
         
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.Add(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.Add(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.Add(new pair(i + 1, a[i]));
    }
     
    vect.Add(new pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.Count == 0)
        return total;
    else
    {
        int sum = 0;
        int sz = vect.Count;
 
        // Iterating through the vector
        for(int i = 1; i + 1 < sz; i++)
        {
             
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect[i].second == 2)
            {
                sum += (vect[i].first -
                        vect[i - 1].first) *
                       (vect[i + 1].first -
                        vect[i].first) - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.Count;
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 5, 4, 2, 9, 8 };
    int n = a.Length;
     
    Console.Write(CntcontSubs(a, n));
}
}
 
// This code is contributed by Amit Katiyar


输出:
13

时间复杂度: O(N 2 ) ,其中N是数组的长度。

有效的方法:这种想法背后的恒等式是,如果一个数字除以4则得到2的余数,则数字不能表示为两个平方的差。因此,该想法是找到所有产生2乘积并减去的子序列。这些来自数组的所有可能子序列。连续子序列的总数可以通过以下公式获得: (N *(N + 1))/ 2

  • 如果数组包含元素0,则包含该元素的所有子序列的乘积变为0。因此,所有这些子序列都可以表示为两个平方的差。
  • 如果在数字除以4时有任何元素将余数2赋给剩余数,则必须避免所有最近的2或0的子序列,因为当遇到2时余数变为4,而当遇到0时余数变为0。

例子:

  • 令arr [] = {6、5、13、10、4、8、14、17}。
  • 当元素除以4时,我们将计算余数。因此,{2,1,1,2,2,0,0,2,1}是给定数组的余数。
  • 在这里,我们得到索引1、4、7的余数2。让我们观察第一个索引的2。
  • 以下是余数数组{2},{2、1},{2、1、1},{2、1、1、1、2},{2、1、1、2、0}…{ 2、1、1、2、0、0、2、1}。
  • 子序列的乘积为{2,2,2,2,4,0…。 0}。
  • 因此,我们得到从索引1到索引3的乘积为2。因此,从索引1到索引3(乘积为2)的总连续子序列为2(即[index-3 – index-1])。
  • 因此,很明显,我们找到元素2或0的最近索引,并忽略所有子序列,直到该索引为止。

下面是上述方法的实现:

C++

// C++ implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
 
#include 
using namespace std;
 
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
int CntcontSubs(int a[], int n)
{
    int prod = 1;
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    vector > vect;
 
    vect.push_back(make_pair(0, 2));
 
    vector two, zero;
 
    // Iterating through the array
    for (int i = 0; i < n; i++) {
 
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.push_back(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.push_back(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.push_back(make_pair(i + 1, a[i]));
    }
    vect.push_back(make_pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.empty())
        return total;
    else {
        int sum = 0;
 
        int pos1 = -1, pos2 = -1, pos3 = -1;
 
        int sz = vect.size();
 
        // Iterating through the vector
        for (int i = 1; i + 1 < sz; i++) {
 
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect[i].second == 2) {
                sum += (vect[i].first
                        - vect[i - 1].first)
                           * (vect[i + 1].first
                              - vect[i].first)
                       - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.size();
    }
}
 
// Driver code
int main()
{
    int a[] = { 5, 4, 2, 9, 8 };
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << CntcontSubs(a, n);
 
    return 0;
}

Java

// Java implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
import java.util.*;
class GFG{
static class pair
{
      int first, second;
    public pair(int first, int second) 
    {
          this.first = first;
        this.second = second;
    }   
}
   
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
static int CntcontSubs(int a[], int n)
{
    int prod = 1;
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    Vector vect = new Vector();
 
    vect.add(new pair(0, 2));
    Vector two = new  Vector();
    Vector zero = new  Vector();
 
    // Iterating through the array
    for (int i = 0; i < n; i++)
    {
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.add(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.add(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.add(new pair(i + 1, a[i]));
    }
    vect.add(new pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.isEmpty())
        return total;
    else
    {
        int sum = 0;
        int pos1 = -1, pos2 = -1, pos3 = -1;
        int sz = vect.size();
 
        // Iterating through the vector
        for (int i = 1; i + 1 < sz; i++)
        {
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect.get(i).second == 2)
            {
                sum += (vect.get(i).first -
                        vect.get(i-1).first) *
                       (vect.get(i+1).first -
                        vect.get(i).first) - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.size();
    }
}
 
// Driver code
public static void main(String[] args)
{
    int a[] = {5, 4, 2, 9, 8};
    int n = a.length;
    System.out.print(CntcontSubs(a, n));
}
}
 
// This code is contributed by shikhasingrajput

Python3

# Python3 implementation to count all the
# contiguous subsequences whose product is
# expressed as the square of the difference
# of two integers
 
# Function to count all the
# contiguous subsequences whose
# product is expressed as the square
# of the difference of two integers
def CntcontSubs(a, n):
     
    prod = 1
 
    # Creating vectors to store
    # the remainders and the
    # subsequences
    vect = []
 
    vect.append((0, 2))
 
    two, zero = [], []
 
    # Iterating through the array
    for i in range(n):
         
        # Finding the remainder when the
        # element is divided by 4
        a[i] = a[i] % 4
 
        # Bringing all the elements in
        # the range [0, 3]
        if (a[i] < 0):
            a[i] = a[i] + 4
 
        # If the remainder is 2, store
        # the index of the
        if (a[i] == 2):
            two.append(i + 1)
 
        # If the remainder is 2, store
        # the index of the
        if (a[i] == 0):
            zero.append(i + 1)
 
        if (a[i] == 0 or a[i] == 2):
            vect.append((i + 1, a[i]))
     
    vect.append((n + 1, 2))
 
    # Finding the total number of subsequences
    total = (n * (n + 1)) // 2
 
    # If there are no numbers which
    # yield the remainder 2
    if (len(two) == 0):
        return total
    else:
        Sum = 0
 
        pos1, pos2, pos3 = -1, -1, -1
 
        sz = len(vect)
 
        # Iterating through the vector
        for i in range(1, sz - 1):
             
            # If the element is 2, find the
            # nearest 2 or 0 and find the
            # number of elements between them
            if (vect[i][1] == 2) :
                Sum += ((vect[i][0] - vect[i - 1][0]) *
                        (vect[i + 1][0] - vect[i][0]) - 1)
 
        # Returning the count
        return (total - Sum - len(two))
 
# Driver Code
a = [ 5, 4, 2, 9, 8 ]
n = len(a)
 
print(CntcontSubs(a, n))
 
# This code is contributed by divyeshrabadiya07

C#

// C# implementation to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
using System;
using System.Collections.Generic;
 
class GFG{
     
class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to count all the
// contiguous subsequences whose
// product is expressed as the square
// of the difference of two integers
static int CntcontSubs(int []a, int n)
{
 
    // Creating vectors to store
    // the remainders and the
    // subsequences
    List vect = new List();
 
    vect.Add(new pair(0, 2));
    List two = new List();
    List zero = new List();
 
    // Iterating through the array
    for(int i = 0; i < n; i++)
    {
         
        // Finding the remainder when the
        // element is divided by 4
        a[i] = a[i] % 4;
 
        // Bringing all the elements in
        // the range [0, 3]
        if (a[i] < 0)
            a[i] = a[i] + 4;
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 2)
            two.Add(i + 1);
 
        // If the remainder is 2, store
        // the index of the
        if (a[i] == 0)
            zero.Add(i + 1);
 
        if (a[i] == 0 || a[i] == 2)
            vect.Add(new pair(i + 1, a[i]));
    }
     
    vect.Add(new pair(n + 1, 2));
 
    // Finding the total number of subsequences
    int total = (n * (n + 1)) / 2;
 
    // If there are no numbers which
    // yield the remainder 2
    if (two.Count == 0)
        return total;
    else
    {
        int sum = 0;
        int sz = vect.Count;
 
        // Iterating through the vector
        for(int i = 1; i + 1 < sz; i++)
        {
             
            // If the element is 2, find the nearest
            // 2 or 0 and find the number of
            // elements between them
            if (vect[i].second == 2)
            {
                sum += (vect[i].first -
                        vect[i - 1].first) *
                       (vect[i + 1].first -
                        vect[i].first) - 1;
            }
        }
 
        // Returning the count
        return total - sum - two.Count;
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int []a = { 5, 4, 2, 9, 8 };
    int n = a.Length;
     
    Console.Write(CntcontSubs(a, n));
}
}
 
// This code is contributed by Amit Katiyar
输出:
13

时间复杂度: O(N) ,其中N是数组的长度。