📌  相关文章
📜  计算保存i * arr [i]> j * arr [j]的数组中的对

📅  最后修改于: 2021-04-23 22:38:41             🧑  作者: Mango

给定整数数组arr [0..n-1],对所有对(arr [i],arr [j])进行计数,以使i * arr [i]> j * arr [j],0 = <我

例子 :

Input : arr[] = {5 , 0, 10, 2, 4, 1, 6}
Output: 5
 Pairs which hold condition i*arr[i] > j*arr[j]
 are (10, 2) (10, 4) (10, 1) (2, 1) (4, 1)

Input  : arr[] = {8, 4, 2, 1}
Output : 2

一个简单的解决方案是运行两个循环。一对一地选取数组的每个元素,然后为每个元素在数组右侧找到保持条件的元素,然后递增计数器并最后返回计数器值。

下面是上述想法的实现:

C++
// C++ program to count all pair that
// hold condition i*arr[i] > j*arr[j]
#include
using namespace std;
 
// Return count of pair in given array
// such that  i*arr[i] > j*arr[j]
int CountPair(int arr[] , int n )
{
    int result = 0; // Initialize result
 
    for (int i=0; i j*arr[j] )
                result ++;
    }
    return result;
}
 
// Driver code
int main()
{
    int arr[] = {5 , 0, 10, 2, 4, 1, 6} ;
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Count of Pairs : "
         << CountPair(arr, n);
    return 0;
}


Java
// Java Code for Count pairs in an
// array that hold i*arr[i] > j*arr[j]
class GFG {
     
    // Return count of pair in given array
    // such that  i*arr[i] > j*arr[j]
    public static int CountPair(int arr[] , int n )
    {
        int result = 0; // Initialize result
      
        for (int i = 0; i < n; i++)
        {
            // Generate all pair and increment
            // counter if the hold given condition
            for (int j = i + 1; j < n; j++)
                if (i*arr[i] > j*arr[j] )
                    result ++;
        }
        return result;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = {5 , 0, 10, 2, 4, 1, 6} ;
        int n = arr.length;
        System.out.println("Count of Pairs : " +
                            CountPair(arr, n));
    }
  }
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python3 Code to Count pairs in an
# array that hold i*arr[i] > j*arr[j]
 
# Return count of pair in given array
# such that i*arr[i] > j*arr[j]
def CountPair(arr , n ):
     
    # Initialize result
    result = 0;
     
    for i in range (0, n):
         
        # Generate all pair and increment
        # counter if the hold given condition
        j = i + 1
        while(j < n):
            if (i * arr[i] > j * arr[j] ):
                result = result +1
            j = j + 1
    return result;
     
# Driver program to test above function */
     
arr = [5, 0, 10, 2, 4, 1, 6]
n = len(arr)
print("Count of Pairs : " , CountPair(arr, n))
 
# This code is contributed by Sam007.


C#
// C# Code to Count pairs in an
// array that hold i*arr[i] > j*arr[j]
using System;
 
class GFG
{
    // Return count of pair in given array
    // such that i*arr[i] > j*arr[j]
    public static int CountPair(int []arr , int n )
    {
        // Initialize result
        int result = 0;
     
        for (int i = 0; i < n; i++)
        {
            // Generate all pair and increment
            // counter if the hold given condition
            for (int j = i + 1; j < n; j++)
                if (i*arr[i] > j*arr[j] )
                    result ++;
        }
        return result;
    }
     
    /* Driver program to test above function */
    public static void Main()
    {
        int []arr = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.Length;
        Console.WriteLine("Count of Pairs : " +
                           CountPair(arr, n));
    }
}
 
// This code is contributed by Sam007


PHP
 j*arr[j]
 
// Return count of pair in given array
// such that i*arr[i] > j*arr[j]
function CountPair($arr , $n )
{
     
    // Initialize result
    $result = 0;
     
 
    for($i = 0; $i < $n; $i++)
    {
         
        // Generate all pair and increment
        // counter if the hold given condition
        for ($j = $i + 1; $j < $n; $j++)
            if ($i *  $arr[$i] > $j * $arr[$j] )
                $result ++;
    }
    return $result;
}
 
    // Driver code
    $arr = array(5, 0, 10, 2, 4, 1, 6) ;
    $n = sizeof($arr);
    echo "Count of Pairs : ",
    CountPair($arr, $n);
     
// This code is contributed by m_kit
?>


Javascript


C++
// C++ program to count all pair that
// hold condition i*arr[i] > j*arr[j]
#include 
using namespace std;
 
/* This function merges two sorted arrays and
   returns inversion count in the arrays.*/
int merge(int arr[], int temp[], int left,
                       int mid, int right)
{
    int inv_count = 0;
 
    int i = left; /* index for left subarray*/
    int j = mid;  /* index for right subarray*/
    int k = left; /* ndex for resultant subarray*/
    while ((i <= mid - 1) && (j <= right))
    {
        if (arr[i] <= arr[j])
            temp[k++] = arr[i++];
        else
        {
            temp[k++] = arr[j++];
 
            inv_count = inv_count + (mid - i);
        }
    }
 
    /* Copy the remaining elements of left
     subarray (if there are any) to temp*/
    while (i <= mid - 1)
        temp[k++] = arr[i++];
 
    /* Copy the remaining elements of right
     subarray (if there are any) to temp*/
    while (j <= right)
        temp[k++] = arr[j++];
 
    /* Copy back the merged elements to original
      array*/
    for (i=left; i <= right; i++)
        arr[i] = temp[i];
 
    return inv_count;
}
 
/* An auxiliary recursive function that sorts
   the input array and returns the number of
   inversions in the array. */
int _mergeSort(int arr[], int temp[], int left,
                                      int right)
{
    int mid, inv_count = 0;
    if (right > left)
    {
        /* Divide the array into two parts and call
          _mergeSortAndCountInv() for each of
          the parts */
        mid = (right + left)/2;
 
        /* Inversion count will be sum of inversions in
           left-part, right-part and number of inversions
           in merging */
        inv_count  = _mergeSort(arr, temp, left, mid);
        inv_count += _mergeSort(arr, temp, mid+1, right);
 
        /*Merge the two parts*/
        inv_count += merge(arr, temp, left, mid+1, right);
    }
 
    return inv_count;
}
 
/* This function sorts the input array and
   returns the number of inversions in the
   array */
int countPairs(int arr[], int n)
{
    // Modify the array so that problem reduces to
    // count inversion problem.
    for (int i=0; i


Java
// Java program to count all pair that
// hold condition i*arr[i] > j*arr[j]
import java.io.*;
 
class GFG
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int arr[], int temp[], int left,
                                   int mid, int right)
    {
        int inv_count = 0;
         
        /* index for left subarray*/
        int i = left;
         
        /* index for right subarray*/
        int j = mid;
        /* ndex for resultant subarray*/
        int k = left;
         
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
     
                inv_count = inv_count + (mid - i);
            }
        }
     
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
     
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
     
        // Copy back the merged elements
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
     
        return inv_count;
    }
     
    /* An auxiliary recursive function
    that sorts the input array and
    returns the number of inversions
    in the array. */
    static int _mergeSort(int arr[], int temp[],
                               int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
     
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
     
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
     
        return inv_count;
    }
     
    // This function sorts the input array and
    // returns the number of inversions in the
    // array
    static int countPairs(int arr[], int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
     
        // Count inversions using same logic as
        // below post
        // https://www.geeksforgeeks.org/counting-inversions/
        int temp[] = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
     
    // Driver code
 
    public static void main (String[] args)
    {
        int arr[] = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.length;
        System.out.print( "Count of Pairs : "
                          + countPairs(arr, n)); 
         
    }
}
 
// This code is contributed by vt_m


Python3
# Python 3 program to count all
# pair that hold condition
# i*arr[i] > j*arr[j]
 
# This function merges two
# sorted arrays and returns
# inversion count in the arrays.
def merge(arr, temp, left, mid, right):
 
    inv_count = 0
 
    i = left # index for left subarray
    j = mid # index for right subarray
    k = left # ndex for resultant subarray
    while ((i <= mid - 1) and (j <= right)):
     
        if (arr[i] <= arr[j]):
            temp[k] = arr[i]
            i += 1
            k += 1
        else:
         
            temp[k] = arr[j]
            k += 1
            j += 1
 
            inv_count = inv_count + (mid - i)
 
    # Copy the remaining elements of left
    # subarray (if there are any) to temp
    while (i <= mid - 1):
        temp[k] = arr[i]
        i += 1
        k += 1
 
    # Copy the remaining elements of right
    # subarray (if there are any) to temp
    while (j <= right):
        temp[k] = arr[j]
        k += 1
        j += 1
 
    # Copy back the merged elements
    # to original array
    for i in range(left, right + 1):
        arr[i] = temp[i]
 
    return inv_count
 
# An auxiliary recursive function
# that sorts the input array and
# returns the number of inversions
# in the array.
def _mergeSort(arr, temp, left, right):
 
    inv_count = 0
    if (right > left):
     
        # Divide the array into two parts
        # and call _mergeSortAndCountInv()
        # for each of the parts
        mid = (right + left) // 2
 
        # Inversion count will be sum of
        # inversions in left-part, right-part x
        # and number of inversions in merging
        inv_count = _mergeSort(arr, temp, left, mid)
        inv_count += _mergeSort(arr, temp,
                                mid + 1, right)
 
        # Merge the two parts
        inv_count += merge(arr, temp, left,    
                           mid + 1, right)
 
    return inv_count
 
# This function sorts the input
# array and returns the number
# of inversions in the array
def countPairs(arr, n):
     
    # Modify the array so that problem
    # reduces to count inversion problem.
    for i in range(n):
        arr[i] = i * arr[i]
 
    # Count inversions using same
    # logic as below post
    # https://www.geeksforgeeks.org/counting-inversions/
    temp = [0] * n
    return _mergeSort(arr, temp, 0, n - 1)
 
# Driver code
if __name__ == "__main__":
    arr = [5, 0, 10, 2, 4, 1, 6]
    n = len(arr)
    print("Count of Pairs : ",
           countPairs(arr, n))
            
# This code is contributed
# by ChitraNayal


C#
// C# program to count all pair that
// hold condition i*arr[i] > j*arr[j]
using System;
 
class GFG
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int []arr, int []temp, int left,
                                int mid, int right)
    {
        int inv_count = 0;
         
        /* index for left subarray*/
        int i = left;
         
        /* index for right subarray*/
        int j = mid;
        /* ndex for resultant subarray*/
        int k = left;
         
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
     
                inv_count = inv_count + (mid - i);
            }
        }
     
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
     
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
     
        // Copy back the merged elements
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
     
        return inv_count;
    }
     
    /* An auxiliary recursive function
    that sorts the input array and
    returns the number of inversions
    in the array. */
    static int _mergeSort(int []arr, int []temp,
                            int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
     
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
     
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
     
        return inv_count;
    }
     
    // This function sorts the input array and
    // returns the number of inversions in the
    // array
    static int countPairs(int []arr, int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
     
        // Count inversions using same logic as
        // below post
        // https://www.geeksforgeeks.org/counting-inversions/
        int []temp = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
     
    // Driver code
 
    public static void Main ()
    {
        int []arr = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.Length;
        Console.WriteLine( "Count of Pairs : "
                        + countPairs(arr, n));
         
    }
}
 
// This code is contributed by anuj_67.


Javascript


输出:

Count of Pairs : 5

时间复杂度:O(n 2 )

这个问题的有效解决方案需要O(n log n)时间。这个想法基于一个有关此问题的有趣事实,即在修改数组以使每个元素与其索引相乘后,此问题将转换为数组中的Count Inversions。
算法 :

Given an array 'arr' and it's size 'n'
1) First traversal array element, i goes from 0 to n-1
   a) Multiple each element with its index arr[i] = arr[i] * i 
2) After that step 1. whole process is similar to Count Inversions in an array. 

下面实现以上思路

C++

// C++ program to count all pair that
// hold condition i*arr[i] > j*arr[j]
#include 
using namespace std;
 
/* This function merges two sorted arrays and
   returns inversion count in the arrays.*/
int merge(int arr[], int temp[], int left,
                       int mid, int right)
{
    int inv_count = 0;
 
    int i = left; /* index for left subarray*/
    int j = mid;  /* index for right subarray*/
    int k = left; /* ndex for resultant subarray*/
    while ((i <= mid - 1) && (j <= right))
    {
        if (arr[i] <= arr[j])
            temp[k++] = arr[i++];
        else
        {
            temp[k++] = arr[j++];
 
            inv_count = inv_count + (mid - i);
        }
    }
 
    /* Copy the remaining elements of left
     subarray (if there are any) to temp*/
    while (i <= mid - 1)
        temp[k++] = arr[i++];
 
    /* Copy the remaining elements of right
     subarray (if there are any) to temp*/
    while (j <= right)
        temp[k++] = arr[j++];
 
    /* Copy back the merged elements to original
      array*/
    for (i=left; i <= right; i++)
        arr[i] = temp[i];
 
    return inv_count;
}
 
/* An auxiliary recursive function that sorts
   the input array and returns the number of
   inversions in the array. */
int _mergeSort(int arr[], int temp[], int left,
                                      int right)
{
    int mid, inv_count = 0;
    if (right > left)
    {
        /* Divide the array into two parts and call
          _mergeSortAndCountInv() for each of
          the parts */
        mid = (right + left)/2;
 
        /* Inversion count will be sum of inversions in
           left-part, right-part and number of inversions
           in merging */
        inv_count  = _mergeSort(arr, temp, left, mid);
        inv_count += _mergeSort(arr, temp, mid+1, right);
 
        /*Merge the two parts*/
        inv_count += merge(arr, temp, left, mid+1, right);
    }
 
    return inv_count;
}
 
/* This function sorts the input array and
   returns the number of inversions in the
   array */
int countPairs(int arr[], int n)
{
    // Modify the array so that problem reduces to
    // count inversion problem.
    for (int i=0; i

Java

// Java program to count all pair that
// hold condition i*arr[i] > j*arr[j]
import java.io.*;
 
class GFG
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int arr[], int temp[], int left,
                                   int mid, int right)
    {
        int inv_count = 0;
         
        /* index for left subarray*/
        int i = left;
         
        /* index for right subarray*/
        int j = mid;
        /* ndex for resultant subarray*/
        int k = left;
         
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
     
                inv_count = inv_count + (mid - i);
            }
        }
     
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
     
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
     
        // Copy back the merged elements
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
     
        return inv_count;
    }
     
    /* An auxiliary recursive function
    that sorts the input array and
    returns the number of inversions
    in the array. */
    static int _mergeSort(int arr[], int temp[],
                               int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
     
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
     
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
     
        return inv_count;
    }
     
    // This function sorts the input array and
    // returns the number of inversions in the
    // array
    static int countPairs(int arr[], int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
     
        // Count inversions using same logic as
        // below post
        // https://www.geeksforgeeks.org/counting-inversions/
        int temp[] = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
     
    // Driver code
 
    public static void main (String[] args)
    {
        int arr[] = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.length;
        System.out.print( "Count of Pairs : "
                          + countPairs(arr, n)); 
         
    }
}
 
// This code is contributed by vt_m

Python3

# Python 3 program to count all
# pair that hold condition
# i*arr[i] > j*arr[j]
 
# This function merges two
# sorted arrays and returns
# inversion count in the arrays.
def merge(arr, temp, left, mid, right):
 
    inv_count = 0
 
    i = left # index for left subarray
    j = mid # index for right subarray
    k = left # ndex for resultant subarray
    while ((i <= mid - 1) and (j <= right)):
     
        if (arr[i] <= arr[j]):
            temp[k] = arr[i]
            i += 1
            k += 1
        else:
         
            temp[k] = arr[j]
            k += 1
            j += 1
 
            inv_count = inv_count + (mid - i)
 
    # Copy the remaining elements of left
    # subarray (if there are any) to temp
    while (i <= mid - 1):
        temp[k] = arr[i]
        i += 1
        k += 1
 
    # Copy the remaining elements of right
    # subarray (if there are any) to temp
    while (j <= right):
        temp[k] = arr[j]
        k += 1
        j += 1
 
    # Copy back the merged elements
    # to original array
    for i in range(left, right + 1):
        arr[i] = temp[i]
 
    return inv_count
 
# An auxiliary recursive function
# that sorts the input array and
# returns the number of inversions
# in the array.
def _mergeSort(arr, temp, left, right):
 
    inv_count = 0
    if (right > left):
     
        # Divide the array into two parts
        # and call _mergeSortAndCountInv()
        # for each of the parts
        mid = (right + left) // 2
 
        # Inversion count will be sum of
        # inversions in left-part, right-part x
        # and number of inversions in merging
        inv_count = _mergeSort(arr, temp, left, mid)
        inv_count += _mergeSort(arr, temp,
                                mid + 1, right)
 
        # Merge the two parts
        inv_count += merge(arr, temp, left,    
                           mid + 1, right)
 
    return inv_count
 
# This function sorts the input
# array and returns the number
# of inversions in the array
def countPairs(arr, n):
     
    # Modify the array so that problem
    # reduces to count inversion problem.
    for i in range(n):
        arr[i] = i * arr[i]
 
    # Count inversions using same
    # logic as below post
    # https://www.geeksforgeeks.org/counting-inversions/
    temp = [0] * n
    return _mergeSort(arr, temp, 0, n - 1)
 
# Driver code
if __name__ == "__main__":
    arr = [5, 0, 10, 2, 4, 1, 6]
    n = len(arr)
    print("Count of Pairs : ",
           countPairs(arr, n))
            
# This code is contributed
# by ChitraNayal

C#

// C# program to count all pair that
// hold condition i*arr[i] > j*arr[j]
using System;
 
class GFG
{
    // This function merges two sorted arrays and
    // returns inversion count in the arrays.
    static int merge(int []arr, int []temp, int left,
                                int mid, int right)
    {
        int inv_count = 0;
         
        /* index for left subarray*/
        int i = left;
         
        /* index for right subarray*/
        int j = mid;
        /* ndex for resultant subarray*/
        int k = left;
         
        while ((i <= mid - 1) && (j <= right))
        {
            if (arr[i] <= arr[j])
                temp[k++] = arr[i++];
            else
            {
                temp[k++] = arr[j++];
     
                inv_count = inv_count + (mid - i);
            }
        }
     
        /* Copy the remaining elements of left
        subarray (if there are any) to temp*/
        while (i <= mid - 1)
            temp[k++] = arr[i++];
     
        /* Copy the remaining elements of right
        subarray (if there are any) to temp*/
        while (j <= right)
            temp[k++] = arr[j++];
     
        // Copy back the merged elements
        // to original array
        for (i = left; i <= right; i++)
            arr[i] = temp[i];
     
        return inv_count;
    }
     
    /* An auxiliary recursive function
    that sorts the input array and
    returns the number of inversions
    in the array. */
    static int _mergeSort(int []arr, int []temp,
                            int left,int right)
    {
        int mid, inv_count = 0;
        if (right > left)
        {
            /* Divide the array into two parts and call
            _mergeSortAndCountInv() for each of
            the parts */
            mid = (right + left) / 2;
     
            // Inversion count will be sum of inversions in
            // left-part, right-part and number of inversions
            // in merging
            inv_count = _mergeSort(arr, temp, left, mid);
            inv_count += _mergeSort(arr, temp, mid+1, right);
     
            /*Merge the two parts*/
            inv_count += merge(arr, temp, left, mid+1, right);
        }
     
        return inv_count;
    }
     
    // This function sorts the input array and
    // returns the number of inversions in the
    // array
    static int countPairs(int []arr, int n)
    {
        // Modify the array so that problem reduces to
        // count inversion problem.
        for (int i = 0; i < n; i++)
            arr[i] = i * arr[i];
     
        // Count inversions using same logic as
        // below post
        // https://www.geeksforgeeks.org/counting-inversions/
        int []temp = new int [n];
        return _mergeSort(arr, temp, 0, n - 1);
    }
     
    // Driver code
 
    public static void Main ()
    {
        int []arr = {5, 0, 10, 2, 4, 1, 6};
        int n = arr.Length;
        Console.WriteLine( "Count of Pairs : "
                        + countPairs(arr, n));
         
    }
}
 
// This code is contributed by anuj_67.

Java脚本


输出:

Count of Pairs : 5

时间复杂度: O(n log n)