给定一个数组arr [] 。数组A的子集的值定义为该子集中所有数字的平方和。任务是计算给定数组的所有可能的非空子集的值之和。
因为,答案可以是大写val mod 1000000007。
例子:
Input: arr[] = {3, 7}
Output: 116
val({3}) = 32 = 9
val({7}) = 72 = 49
val({3, 7}) = 32 + 72 = 9 + 49 = 58
9 + 49 + 58 = 116
Input: arr[] = {1, 1, 1}
Output: 12
天真的方法:一种简单的方法是找到所有子集,然后对子集中的每个元素求平方并将其添加到结果中。该方法的时间复杂度将为O(2 N )
高效方法:可以观察到,在给定数组的所有可能子集中,每个元素将出现2 N – 1次,其中N是数组的大小。
因此,任何元素X在总和中的贡献为2 N – 1 * X 2 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
const int mod = 1e9 + 7;
// Function to return (2^P % mod)
long long power(int p)
{
long long res = 1;
for (int i = 1; i <= p; ++i) {
res *= 2;
res %= mod;
}
return res % mod;
}
// Function to return the sum of squares of subsets
long long subset_square_sum(vector& A)
{
int n = (int)A.size();
long long ans = 0;
// Sqauaring the elements
// and adding it to ans
for (int i : A) {
ans += (1LL * i * i) % mod;
ans %= mod;
}
return (1LL * ans * power(n - 1)) % mod;
}
// Driver code
int main()
{
vector A = { 3, 7 };
cout << subset_square_sum(A);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
static final int mod = (int)(1e9 + 7);
// Function to return (2^P % mod)
static long power(int p)
{
long res = 1;
for (int i = 1; i <= p; ++i)
{
res *= 2;
res %= mod;
}
return res % mod;
}
// Function to return the sum of squares of subsets
static long subset_square_sum(int A[])
{
int n = A.length;
long ans = 0;
// Sqauaring the elements
// and adding it to ans
for (int i : A)
{
ans += (1 * i * i) % mod;
ans %= mod;
}
return (1 * ans * power(n - 1)) % mod;
}
// Driver code
public static void main (String[] args)
{
int A[] = { 3, 7 };
System.out.println(subset_square_sum(A));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
mod = 10**9 + 7
# Function to return (2^P % mod)
def power(p):
res = 1
for i in range(1, p + 1):
res *= 2
res %= mod
return res % mod
# Function to return the sum of
# squares of subsets
def subset_square_sum(A):
n = len(A)
ans = 0
# Squaring the elements
# and adding it to ans
for i in A:
ans += i * i % mod
ans %= mod
return ans * power(n - 1) % mod
# Driver code
A = [3, 7]
print(subset_square_sum(A))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
static readonly int mod = (int)(1e9 + 7);
// Function to return (2^P % mod)
static long power(int p)
{
long res = 1;
for (int i = 1; i <= p; ++i)
{
res *= 2;
res %= mod;
}
return res % mod;
}
// Function to return the sum of squares of subsets
static long subset_square_sum(int []A)
{
int n = A.Length;
long ans = 0;
// Sqauaring the elements
// and adding it to ans
foreach (int i in A)
{
ans += (1 * i * i) % mod;
ans %= mod;
}
return (1 * ans * power(n - 1)) % mod;
}
// Driver code
public static void Main (String[] args)
{
int []A = { 3, 7 };
Console.WriteLine(subset_square_sum(A));
}
}
// This code is contributed by 29AjayKumar
输出:
116
时间复杂度: O(N)