Summing Pieces


Problem Statement :


Consider an array, A, of length n. We can split A into contiguous segments called pieces and store them as another array, B. For example, if A = [1,2,3], we have the following arrays of pieces:

 B = [(1),(2),(3)] contains three 1-element pieces.
 B = [(1,2),(3)] contains two pieces, one having 2 elements and the other having 1 element.
 B = [(1),(2,3)] contains two pieces, one having 1 element and the other having 2 elements.
 B = [(1,2,3)] contains one 3-element piece.
We consider the value of a piece in some array B to be (sum of all numbers in the piece) * (length of piece), and we consider the total value of some array B to be the sum of the values for all pieces in that B. For example, the total value of B = [1,2,4),(5,1),(2)] is (1+2+4)*3+(5+1)*2+(2)*1 = 35.

Given A, find the total values for all possible B's, sum them together, and print this sum modulo (10^9 +  7) on a new line.

Input Format

The first line contains a single integer, n, denoting the size of array A.
The second line contains n space-separated integers describing the respective values in A (i.e.,a0,a1,...,an-1).

Constraints
1 <= n <= 10^6
1 <= ai <= 10^9

Output Format

Print a single integer denoting the sum of the total values for all piece arrays (B's) of A, modulo (10^9 + 7).



Solution :



title-img


                            Solution in C :

In C++ :





//It’s never too late to become what you might have been....
 #include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define inf 1000000000000
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define S second
#define F first
#define boost1 ios::sync_with_stdio(false);
#define boost2 cin.tie(0);
#define mem(a,val) memset(a,val,sizeof a)
#define endl "\n"
#define maxn 1000001

ll power[maxn],sub[maxn],pre[maxn],suff[maxn],a[maxn];

ll ways(ll x)
{
	if(x==0)
	return 1;
	return power[x-1];
}
int main()
{
	boost1;boost2;	
	ll i,j,n,q,x,y,sum=0,ans=0;
	power[0]=1;
	for(i=1;i<=1000000;i++)
	power[i]=(2*power[i-1])%mod;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		cin>>a[i];
		sum+=a[i];
		sum%=mod;
	}	
	for(i=1;i<=n;i++)
	pre[i]=(pre[i-1]+a[i])%mod;
	for(i=n;i>=1;i--)
	suff[i]=(suff[i+1]+a[i])%mod;
	
	sub[1]=sum;
	for(i=2;i<=n;i++)
	{
		sub[i]=sub[i-1];
		sub[i]=(sub[i]+suff[i])%mod;
		sub[i]=(sub[i]-suff[n-i+2]+mod)%mod;
	}	

	for(i=1;i<=n-2;i++)
	{
		x=sub[i];
		x=(x-pre[i]+mod)%mod;
		x=(x-suff[n-i+1]+mod)%mod;
		ans=(ans+(((i*power[n-i-2])%mod)*x)%mod)%mod;
	}
	for(i=1;i<=n;i++)
	ans=(ans+(((i*pre[i])%mod)*ways(n-i))%mod)%mod;
	for(i=n;i>1;i--)
	ans=(ans+((((n-i+1)*suff[i])%mod)*ways(i-1))%mod)%mod;
	cout<<ans;
	return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        int n = in.nextInt();
        long sum = 0;
        long[] powers2 = new long[n+1];
        powers2[0] = 1;
        for(int i=1; i<=n; i++)
            powers2[i] = (powers2[i-1] << 1) % 1000000007;
        
        for(int i=1; i<=n; i++){
            long left = ((powers2[i] - 1) * powers2[n-i]) % 1000000007;
            long right = ((powers2[1+n-i]-1) * powers2[i-1]) % 1000000007;
            long v = left + right - powers2[n-1];
            sum = (sum + (v * in.nextLong())) % 1000000007;
        }
        
        System.out.println(sum);
        
    }
}








In C :





#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef long long int LL;

#define din(n) scanf("%d",&n)
#define dout(n) printf("%d\n",n)
#define llin(n) scanf("%lld",&n)
#define llout(n) printf("%lld\n",n)
#define strin(n) scanf(" %s",n)
#define strout(n) printf("%s\n",n)

int arr[1000005];
int dp[1000005];
int m = 1e9 + 7;
int mod=1e9+7;

int mult(int a,int b)
{
	LL tmp = (LL)a*(LL)b ;
	tmp = tmp%m;
	return (int)tmp;
}

int add(int a, int b)
{
	LL tmp = (LL)a + (LL)b;
	tmp = tmp%m;
	return (int)tmp;
}

int max(int a, int b)
{
	if(a>b) return a; return b;
}

long long po(int x, int y)
{
	int pro=1;
	while(y>0)
	{
		if(mod==1)
			return(0);
		else if(y&1 != 0)
			pro = mult(pro, x);
		x = mult(x,x);
		y=y>>1;
	}
	return pro;
}

int main()
{
	int n; din(n);
	for(int i=0;i<n;i++) 
	{
		din(arr[i]);
	}
	dp[0] = po(2,n) - 1;
	dp[n-1] = po(2,n) - 1;
	int len1 = n-2, len2 = 0;
	for(int i=1;i<=n/2;i++)
	{
		dp[i] = add(dp[i-1], (po(2, len1--)-po(2,len2++))%m ); // mod
		dp[n-i-1] = dp[i];
	}
	int ans = 0;
	for(int i=0;i<n;i++)
	{
		//printf("%d ", dp[i]);
		ans = add(ans, mult(arr[i], dp[i]));
	}
	//printf("\n");
	dout(ans);
	return(0);
}








In Python3 :





import math

n = int(input())
A = list(map(int,input().split()))
T = [0]*n
MOD = 10**9 +7

def pow_mod(x, y):
    number = 1
    while y:
        if y & 1:
            number = number * x % MOD
        y >>= 1
        x = x * x % MOD
    return number

mem = pow_mod(2,n) + pow_mod(2,n-1)
ans = 0
k = 0
for i in range(1,math.ceil(n/2)+1):
    temp = mem - pow_mod(2,n-i) - pow_mod(2,i-1) 
    T[i-1] = temp
    T[n-i] = temp

# print(T)

for a in A:
    # print(k)
    ans = (ans + T[k]*a)%MOD
    k+=1
    
print(ans)
                        








View More Similar Problems

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →