📌  相关文章
📜  查找可以将一个数组分为相等和的子数组的和

📅  最后修改于: 2021-06-26 13:02:12             🧑  作者: Mango

给定一个整数数组arr [] ,任务是找到sum的所有值,以便对于sum [i]值,该数组可以划分为sum等于sum [i]的子数组。如果不能将array分成相等总和的子数组,则输出-1

例子:

方法:制作一个前缀和数组P [] ,其中P [i]存储从索引0i的元素之和。总和S的除数只能是可能的子数组和。因此,对于每个除数,如果除数之和等于总和S的所有倍数都存在于数组P []中,那么那将是一个可能的子数组和。在地图中将P []的所有元素标记为1,以便查找。可以在sqrt(S)时间中检查所有除数。

下面是上述方法的实现:

C++
// C++ program to find the sums for which an array
// can be divided into subarrays of equal sum.
#include 
using namespace std;
  
// Function to find the sums for which an array
// can be divided into subarrays of equal sum
void getSum(int a[], int n)
{
    int P[n];
  
    // Creating prefix sum array
    P[0] = a[0];
    for (int i = 1; i < n; i++)
        P[i] = a[i] + P[i - 1];
  
    // Total Sum
    int S = P[n - 1];
  
    // Initializing a Map for look-up
    map hash;
  
    // Setting all the present sum as 1
    for (int i = 0; i < n; i++)
        hash[P[i]] = 1;
  
    // Set to store the subarray sum
    set res;
  
    // Check the divisors of S
    for (int i = 1; i * i <= S; i++) {
        if (S % i == 0) {
            bool pres = true;
  
            int div1 = i, div2 = S / i;
  
            // Check if all multiples of div1 present or not
            for (int j = div1; j <= S; j += div1) {
                if (hash[j] != 1) {
                    pres = false;
                    break;
                }
            }
  
            // If all multiples are present
            if (pres and div1 != S)
                res.insert(div1);
  
            pres = true;
  
            // Check if all multiples of div2 present or not
            for (int j = S / i; j <= S; j += S / i) {
                if (hash[j] != 1) {
                    pres = false;
                    break;
                }
            }
  
            // If all multiples are present
            if (pres and div2 != S)
                res.insert(div2);
        }
    }
  
    // If array cannot be divided into 
    // sub-arrays of equal sum
    if(res.size() == 0) {
        cout << "-1";
        return;
    }
  
    // Printing the results
    for (auto i : res)
        cout << i << " ";
}
  
// Driver code
int main()
{
    int a[] = { 1, 2, 1, 1, 1, 2, 1, 3 };
  
    int n = sizeof(a) / sizeof(a[0]);
  
    getSum(a, n);
  
    return 0;
}


Java
// Java program to find the sums for which an array 
// can be divided into subarrays of equal sum. 
import java.util.HashMap;
import java.util.HashSet;
  
class GFG {
  
    // Function to find the sums for which an array
    // can be divided into subarrays of equal sum
    public static void getSum(int[] a, int n) 
    {
        int[] P = new int[n];
  
        // Creating prefix sum array
        P[0] = a[0];
        for (int i = 1; i < n; i++)
            P[i] = a[i] + P[i - 1];
  
        // Total Sum
        int S = P[n - 1];
  
        HashMap hash = new HashMap<>();
  
        // Setting all the present sum as 1
        for (int i = 0; i < n; i++)
            hash.put(P[i], 1);
  
        // Set to store the subarray sum
        HashSet res = new HashSet<>();
  
        // Check the divisors of S
        for (int i = 1; i * i <= S; i++) 
        {
            if (S % i == 0)
            {
                boolean pres = true;
  
                int div1 = i, div2 = S / i;
  
                // Check if all multiples of div1 present or not
                for (int j = div1; j <= S; j += div1)
                {
                    if (hash.get(j) == null || hash.get(j) != 1)
                    {
                        pres = false;
                        break;
                    }
                }
  
                // If all multiples are present
                if (pres && div1 != S)
                    res.add(div1);
  
                pres = true;
  
                // Check if all multiples of div2 present or not
                for (int j = S / i; j <= S; j += S / i) 
                {
                    if (hash.get(j) == null || hash.get(j) != 1)
                    {
                        pres = false;
                        break;
                    }
                }
  
                // If all multiples are present
                if (pres && div2 != S)
                    res.add(div2);
            }
        }
  
        // If array cannot be divided into
        // sub-arrays of equal sum
        if (res.size() == 0)
        {
            System.out.println("-1");
            return;
        }
  
        // Printing the results
        for (int i : res)
            System.out.print(i + " ");
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int[] a = { 1, 2, 1, 1, 1, 2, 1, 3 };
        int n = a.length;
        getSum(a, n);
    }
}
  
// This code is contributed by
// sanjeev2552


Python3
# Python3 program to find the sums for 
# which an array can be divided into 
# subarrays of equal sum. 
  
# from math lib import sqrt function
from math import sqrt
  
# Function to find the sums for which 
# an array can be divided into subarrays 
# of equal sum 
def getSum(a, n) :
      
    P = [0] * n 
  
    # Creating prefix sum array 
    P[0] = a[0]
    for i in range(1, n) : 
        P[i] = a[i] + P[i - 1]
  
    # Total Sum 
    S = P[n - 1] 
  
    # Initializing a Map for look-up 
    hash = {}
  
    # Setting all the present sum as 1 
    for i in range(n) :
        hash[P[i]] = 1
  
    # Set to store the subarray sum 
    res = set()
  
    # Check the divisors of S 
    for i in range(1, int(sqrt(S)) + 1) : 
        if (S % i == 0) :
            pres = True; 
  
            div1 = i
            div2 = S // i
  
            # Check if all multiples of 
            # div1 present or not 
            for j in range(div1 , S + 1, div1) :
                  
                if j not in hash.keys() :
                    pres = False
                    break
  
            # If all multiples are present 
            if (pres and div1 != S) :
                res.add(div1)
  
            pres = True
  
            # Check if all multiples of div2 
            # present or not 
            for j in range(S // i , S + 1 , S // i) : 
                if j not in hash.keys():
                    pres = False; 
                    break
  
            # If all multiples are present 
            if (pres and div2 != S) :
                res.add(div2)
  
    # If array cannot be divided into 
    # sub-arrays of equal sum 
    if(len(res) == 0) :
        print("-1") 
        return
  
    # Printing the results 
    for i in res :
        print(i, end = " ")
  
# Driver code 
if __name__ == "__main__" :
  
    a = [ 1, 2, 1, 1, 1, 2, 1, 3 ]
  
    n = len(a)
  
    getSum(a, n)
  
# This code is contributed by Ryuga


C#
// C# program to find the sums for which
// an array can be divided into subarrays
// of equal sum. 
using System;
using System.Collections.Generic;
  
class GFG 
{
  
// Function to find the sums for which 
// an array can be divided into subarrays
// of equal sum
public static void getSum(int[] a, int n) 
{
    int[] P = new int[n];
  
    // Creating prefix sum array
    P[0] = a[0];
    for (int i = 1; i < n; i++)
        P[i] = a[i] + P[i - 1];
  
    // Total Sum
    int S = P[n - 1];
  
    Dictionary hash = new Dictionary();
  
    // Setting all the present sum as 1
    for (int i = 0; i < n; i++)
        if(!hash.ContainsKey(P[i]))
            hash.Add(P[i], 1);
  
    // Set to store the subarray sum
    HashSet res = new HashSet();
  
    // Check the divisors of S
    for (int i = 1; i * i <= S; i++) 
    {
        if (S % i == 0)
        {
            Boolean pres = true;
  
            int div1 = i, div2 = S / i;
  
            // Check if all multiples of 
            // div1 present or not
            for (int j = div1; j <= S; j += div1)
            {
                if (!hash.ContainsKey(j) || 
                     hash[j] != 1)
                {
                    pres = false;
                    break;
                }
            }
  
            // If all multiples are present
            if (pres && div1 != S)
                res.Add(div1);
  
            pres = true;
  
            // Check if all multiples of 
            // div2 present or not
            for (int j = S / i;
                     j <= S; j += S / i) 
            {
                if (hash[j] == 0 || 
                    hash[j] != 1)
                {
                    pres = false;
                    break;
                }
            }
  
            // If all multiples are present
            if (pres && div2 != S)
                res.Add(div2);
        }
    }
  
    // If array cannot be divided into
    // sub-arrays of equal sum
    if (res.Count == 0)
    {
        Console.WriteLine("-1");
        return;
    }
  
    // Printing the results
    foreach (int i in res)
        Console.Write(i + " ");
}
  
// Driver code
public static void Main(String[] args)
{
    int[] a = { 1, 2, 1, 1, 1, 2, 1, 3 };
    int n = a.Length;
    getSum(a, n);
}
}
  
// This code is contributed by PrinciRaj1992


输出:
3 4 6

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。