📌  相关文章
📜  从给定的两个数组中查找子数组,以使它们具有相等的总和

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

给定两个大小相等的数组A []B [] ,即N包含从1N的整数。任务是从给定数组中找到子数组,以使它们具有相等的总和。打印此类子数组的索引。如果没有这样的子数组,则打印-1

例子:

方法:A i是在第一i个元素和B分别表示Ĵ第j个元素的总和的总和。在不失一般性的前提下,我们假设A n <= B n
现在B n > = A n > = A i 。因此,对于每个A i,我们都可以找到最小的j,使得A i <= B j 。对于每个我,我们都找到了区别
B j – A i
如果差为0,那么我们就完成了,因为A中从1到i以及B中从1到j的元素具有相同的和。假设差分不为0。那么差分必须在[1,n-1]范围内。

现在有n个这样的差异(对应于每个索引),但只有(n-1)个可能的值,因此至少有两个索引会产生相同的差异(根据Pigeonhole原理)。令A j – B y = A i – B x 。重新排列后,我们得到A j – A i = B y – B x 。因此,所需的子数组是A中的[i + 1,j]和B中的[x + 1,y]

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to print the valid indices in the array
void printAns(int x, int y, int num)
{
    cout << "Indices in array " << num << " : ";
    for (int i = x; i < y; ++i) {
        cout << i << ", ";
    }
    cout << y << "\n";
}
  
// Function to find sub-arrays from two
// different arrays with equal sum
void findSubarray(int N, int a[], int b[], bool swap)
{
  
    // Map to store the indices in A and B
    // which produce the given difference
    std::map > index;
    int difference;
    index[0] = make_pair(-1, -1);
    int j = 0;
    for (int i = 0; i < N; ++i) {
  
        // Find the smallest j such that b[j] >= a[i]
        while (b[j] < a[i]) {
            j++;
        }
        difference = b[j] - a[i];
  
        // Difference encountered for the second time
        if (index.find(difference) != index.end()) {
  
            // b[j] - a[i] = b[idx.second] - a[idx.first]
            // b[j] - b[idx.second] = a[i] = a[idx.first]
            // So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j]
            if (swap) {
                pair idx = index[b[j] - a[i]];
  
                printAns(idx.second + 1, j, 1);
                printAns(idx.first + 1, i, 2);
            }
            else {
                pair idx = index[b[j] - a[i]];
                printAns(idx.first + 1, i, 1);
                printAns(idx.second + 1, j, 2);
            }
            return;
        }
  
        // Store the indices for difference in the map
        index[difference] = make_pair(i, j);
    }
  
    cout << "-1";
}
  
// Utility function to calculate the
// cumulative sum of the array
void cumulativeSum(int arr[], int n)
{
    for (int i = 1; i < n; ++i)
        arr[i] += arr[i - 1];
}
  
// Driver code
int main()
{
    int a[] = { 1, 2, 3, 4, 5 };
    int b[] = { 6, 2, 1, 5, 4 };
    int N = sizeof(a) / sizeof(a[0]);
  
    // Function to update the arrays
    // with their cumulative sum
    cumulativeSum(a, N);
    cumulativeSum(b, N);
  
    if (b[N - 1] > a[N - 1]) {
        findSubarray(N, a, b, false);
    }
    else {
  
        // Swap is true as a and b are swapped during
        // function call
        findSubarray(N, b, a, true);
    }
  
    return 0;
}


Python3
# Python3 implementation of the approach 
  
# Function to print the valid indices in the array 
def printAns(x, y, num): 
   
    print("Indices in array", num, ":", end = " ") 
    for i in range(x, y):  
        print(i, end = ", ") 
       
    print(y) 
  
# Function to find sub-arrays from two 
# different arrays with equal sum 
def findSubarray(N, a, b, swap): 
   
    # Map to store the indices in A and B 
    # which produce the given difference 
    index = {} 
    difference, j = 0, 0 
    index[0] = (-1, -1)
      
    for i in range(0, N):  
  
        # Find the smallest j such that b[j] >= a[i] 
        while b[j] < a[i]:  
            j += 1 
           
        difference = b[j] - a[i] 
  
        # Difference encountered for the second time 
        if difference in index:  
  
            # b[j] - a[i] = b[idx.second] - a[idx.first] 
            # b[j] - b[idx.second] = a[i] = a[idx.first] 
            # So sub-arrays are a[idx.first+1...i] and b[idx.second+1...j] 
            if swap:  
                idx = index[b[j] - a[i]] 
                printAns(idx[1] + 1, j, 1) 
                printAns(idx[0] + 1, i, 2) 
               
            else:
                idx = index[b[j] - a[i]] 
                printAns(idx[0] + 1, i, 1) 
                printAns(idx[1] + 1, j, 2) 
               
            return 
           
        # Store the indices for difference in the map 
        index[difference] = (i, j) 
       
    print("-1") 
   
# Utility function to calculate the 
# cumulative sum of the array 
def cumulativeSum(arr, n): 
   
    for i in range(1, n): 
        arr[i] += arr[i - 1] 
   
# Driver code 
if __name__ == "__main__": 
   
    a = [1, 2, 3, 4, 5]  
    b = [6, 2, 1, 5, 4]  
    N = len(a) 
  
    # Function to update the arrays 
    # with their cumulative sum 
    cumulativeSum(a, N) 
    cumulativeSum(b, N) 
  
    if b[N - 1] > a[N - 1]:  
        findSubarray(N, a, b, False) 
       
    else:
  
        # Swap is true as a and b are 
        # swapped during function call 
        findSubarray(N, b, a, True) 
  
# This code is contributed by Rituraj Jain


输出:
Indices in array 1 : 0, 1, 2
Indices in array 2 : 0