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

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →