Problem:


Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

2 \leq N \leq 2\times 10^5

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829



Sample input:
3
1 2 3


Sample output:
11

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split()]

mod = 10 ** 9 + 7

sum = [0] * N
A = A[::-1]
sum[0] = A[0]
for i in range(1, N) :
  sum[i] = (sum[i - 1] + A[i]) % mod
  
sum = sum[::-1]
A = A[::-1]

ret = 0
for i in range(N - 1) :
  ret += A[i] * sum[i + 1] % mod
  ret %= mod
  
print(ret)

Submission status: Accepted

Solution code:
import sys

def solve():
      input = sys.stdin.readline
      N = int(input())
      A = [int(a) for a in input().split()]
      sumA = 0
      mod = 7 + 10 ** 9
      for a in A:
            sumA += a
            sumA %= mod
      ans = 0
      for a in A:
            ans += ((sumA - a + mod) * a) % mod
            ans %= mod
      print((ans * pow(2, mod-2, mod)) % mod)

      return 0

if __name__ == "__main__":
      solve()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(e) for e in input().split()]

s = sum(a)

r = 0
for i in range(n):
    s -= a[i]
    r += a[i] * s
    r %= 10 ** 9 + 7

print(r)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
import copy
# from fractions import gcd

MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)

n = int(input())
A = list(map(int, input().split()))

su = [0]*n
su[-1] = A[-1]
for i in reversed(range(n-1)):
    su[i] = (A[i]+su[i+1])%MOD

ans = 0
for i in range(n-1):
    ans = (ans + A[i]*su[i+1])%MOD

print(ans)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

n = int(readline())
a = list(map(int,readline().split()))

cum = [0]*n

for i in range(n-2,-1,-1):
    cum[i] += cum[i+1] + a[i+1]
    cum[i] %= mod

ans = 0

for i in range(n):
    ans = (ans + a[i]*cum[i])%mod

print(ans)

Submission status: Accepted

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]

M = 10**9+7
n = inp()
x = ip()

sm = sum(x)
sq = sm*sm
ans = 0
for i in x: ans += i*i
ans = (sq-ans)//2
print(ans%M)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = 0; c = 0
for i in range(n): b += a[i]; c += a[i]**2
print((b**2-c)//2%(10**9+7))

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int, input().split()))
MOD=10**9+7
tmp1 = 0
tmp2 = 0
for a in A:
    tmp1 += a
    tmp2 += (a**2)

ans = (tmp1**2 - tmp2)//2
print(ans%MOD)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, *a = map(int, open(0).read().split())
s = ans = 0
MOD = 10**9+7
for b, c in zip(a, a[1:]):
    s = (s + (b % MOD)) % MOD
    ans = (ans + s * (c % MOD) % MOD) % MOD
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split(" ")))
    total_a = sum(a)
    total = 0
    for i in range(n):
        total_a-=a[i]
        total+=(a[i] * total_a)%(10**9+7)
    print(total%(10**9+7))

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
p=10**9+7
suma = [0]*n
suma[0] = 0
for i in range(1,n):
  suma[i] = (suma[i-1] + a[i-1])%p

ans = 0
for i in range(n):
  ans = (ans + ((a[i] % p) * suma[i])%p)%p
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
n=int(input())
a=list(map(int, input().split()))
acc = list(accumulate(a[::-1]))[::-1]
ans=0
for i in range(n-1):
    ans+=a[i]*acc[i+1]
    ans%=10**9+7
print(ans)

Submission status: Accepted

Solution code:
MOD = 10**9 + 7


def main():
    N = int(input())
    A = [int(i) for i in input().split()]
    from itertools import accumulate
    S = list(accumulate([0] + A))
    ans = 0
    for i in range(N-1):
        ans += A[i] * (S[N] - S[i+1])
        ans %= MOD
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
mod = 10**9+7
total = sum(a)
ret = 0
for i in range(n):
    ret += ((total - a[i]) * a[i])
print((ret//2) % mod)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().rstrip().split(" ")))
k = [0 for i in range(N + 1)]
ans = 0
for i in range(N):
    k[i + 1] = k[i] + A[i]
for i in range(N):
    ans += k[i] * A[i]
    ans %= 10 ** 9 + 7
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))

sm=sum(l)
ans=0

for i in l:
  sm-=i
  ans+=i*sm
  ans%=1000000007
print(ans)

Submission status: Accepted

Solution code:
def read_ints():
    return map(int, input().split(' '))


mod = int(1e9 + 7)


def fexp(x, y):
    ret = 1
    while y > 0:
        if y % 2 == 1:
            ret = ret * x % mod
        x = x * x % mod
        y = y // 2
    return ret


input()
a = list(read_ints())
s = sum(a)
ans = 0
for i in a:
    ans = (ans + i * (s - i)) % mod
print(ans * fexp(2, mod - 2) % mod)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

a1 = sum(a)**2 
a2 = 0
for i in range(len(a)):
    a2 = (a2 + (a[i]**2)) 

ans = ((a1 - a2) // 2) % 1000000007
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
arr = list(map(int,input().split()))
mod = 10**9 + 7
som = sum(arr)
ans = 0
for i in range(n):
    ans+=(som-arr[i])*arr[i]
print((ans//2)%mod)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
mod = 10**9 + 7

sum1 = 0
sum2 = 0
for a in A:
  sum1 = (sum1 + a)
  sum2 = (sum2 + a**2)

answer = ((sum1**2 - sum2) // 2) % mod
print(answer)

Submission status: Accepted

Solution code:
import math
import pprint
import fractions
import collections
import itertools
from decimal import *
from collections import deque
from bisect import *
N=int(input())
A=list(map(int,input().split()))
cuml=[0]*N
p=10**9+7
for i in range(N-1):
    cuml[i+1]=(cuml[i]+A[i])%p
#print(cuml)
ans=0
for i in range(N):
    ans=(ans+A[i]*cuml[i])%p
print(ans)

Submission status: Accepted

Solution code:
N = input()
arr = list(map(int,input().split(" ")))
MOD = int(1e9+7)
sum_arr = sum(arr) % MOD
res = 0
for a in arr:
    sum_arr = (sum_arr-a)%MOD
    res = (res+ sum_arr*a)%MOD
print(res)

Submission status: Accepted

Solution code:
mod = 10**9+7
N = int(input())
A = list(map(int,input().split()))
AA = 0
for i in range(N):
    AA += A[i]**2
    AA %= mod
print((sum(A)**2-AA)*pow(2,mod-2,mod) % mod)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N= int(input().rstrip('\n'))
As = [int(x) for x in input().rstrip('\n').split()]
s = sum(As)**2
b = sum(x**2 for x in As)
print(((s-b)//2)%1000000007)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

mod = 10 ** 9 + 7
N = 1000

#逆元テーブル
inv_t = [0]+[1]
for i in range(2, N):
  inv_t += [inv_t[mod % i] * (mod - int(mod / i)) % mod]

#階乗計算
kai = [1, 1]
rev_kai = [1, inv_t[1]]
for i in range(2, N):
	kai.append(kai[-1] * i % mod)
	rev_kai.append(rev_kai[-1] * inv_t[i] % mod)

# コンビネーション計算
def cmb(n, r):
	return kai[n] * rev_kai[r] * rev_kai[n-r] % mod

tmp1 = 0
tmp2 = 0
mod = 10 ** 9 + 7
for ai in a:
    tmp1 += (ai ** 2) % mod
    tmp1 %= mod
    tmp2 += ai
    tmp2 %= mod

print((tmp2 ** 2 - tmp1) * inv_t[2] % mod)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

mod = 10**9+7
sa = sum(A)%mod

ans = 0
for i in range(N):
    ans += (sa-A[i]) * A[i]
    ans %= mod

if ans%2== 1:
    ans += mod

print((ans//2)%mod)

Submission status: Accepted

Solution code:
n=int(input())
L=list(map(int,input().split()))
mod=10**9+7
tmp1=sum(L)
tmp2=0
for i in range(n):
    tmp2+=(L[i])**2
print(((tmp1**2-tmp2)//2)%mod)

Submission status: Accepted

Solution code:
MOD=10**9+7

N=int(input())
A=list(map(int, input().split()))
X=[0]*N
X[0]=A[0]+0
X[0]%=MOD
for i in range(1, N):
  X[i]=X[i-1]+A[i]
  X[i]%=MOD
  
ans=0
for i in range(1, N):
  tmp=X[i-1]*A[i]%MOD
  ans=(ans+tmp)%MOD
print(ans)

Submission status: Accepted

Solution code:
MOD = int(1e9 + 7)
n = int(input())
a = list(map(int, input().split()))
sum_a = 0
for i in range(n):
    sum_a += a[i]
    sum_a %= MOD
ans = 0
for i in a:
    sum_a -= i
    ans += sum_a * i % MOD
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
M = 10 ** 9 + 7

N = int(input())
A_list = list(map(int, input().split()))

total = sum(A_list)

m = 0
for i in range(N - 1):
	A = A_list[i]
	total -= A
	m = (m + A * total) % M

print(m)

Submission status: Accepted

Solution code:
(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]

S = sum(A)
MOD = 10 ** 9 + 7
print(((S * S - sum(x * x for x in A)) // 2) % MOD)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def main():
    n = int(input())
    a = list(map(int, input().split()))
    
    sub = 0
    ans = 0
    mod = pow(10, 9)+7
    for i in range(n):
        ans = (ans + sub*a[i])%mod
        sub += a[i]
    
    print(ans)
    
    
    
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
mod = pow(10, 9) + 7
b = [0] * (n + 1)
for i in range(n):
    b[i + 1] = a[i] + b[i]
ans = 0
for i in range(n - 1):
    ans += (b[n] - b[i + 1]) * a[i]
    ans %= mod
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
N= int(input())
A=list(map(int,input().split()))

cA = [A[-1]]

MOD = 10**9+7

for i in range(N-1):
    cA.append(cA[-1]+A[-2-i])

ans=0
cA.reverse()


for i in range(N-1):
    ans+=A[i]*cA[i+1]
    ans=ans%MOD
    
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = LIST()

s = sum(A)
ans = 0

for x in A:
    ans += x * (s-x)
    ans %= mod
ans = ans*pow(2, mod-2, mod)
ans %= mod
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

MOD = 10**9+7
cum = [0 for _ in range(n)]
cum[0] = a[0]
for i in range(1, n):
    cum[i] = cum[i-1]+a[i]

ans = 0
for i in range(n):
    ans += a[i]*(cum[n-1]-cum[i])
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
arr = [0]*(n+1)
ans = 0
mod = 10**9+7
for i in range(n):
  arr[i+1] += arr[i]+a[i]
  
for i in range(n):
  ans += (a[i]*(arr[n]-arr[i+1]))%mod
print(ans%mod)

Submission status: Accepted

Solution code:
from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
from  itertools import accumulate

def get_int():return int(stdin.readline().strip())
def get_tuple():return map(int, stdin.readline().split())
def get_list():return list(map(int, stdin.readline().split()))

n = get_int()
ls = get_list()
mod = 10**9+7
pref_sum = list(accumulate(ls))

ans = 0
for i in range(1,n):
    ans = (ans+ls[i]*(pref_sum[i]-ls[i]))%mod
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
*A, = map(int,input().split())

mod = 10**9+7

ans = ((sum(A)%mod)**2)%mod
ans -= sum(a*a%mod for a in A)%mod
ans %= mod
ans *= pow(2,mod-2,mod)
ans %= mod

print(ans)

Submission status: Accepted

Solution code:
mod = 10**9+7
N = int(input())
A = list(map(int,input().split()))

ans = 0
for i in range(N):
    ans += A[i]
    ans %= mod
ans = ans**2%mod

for i in range(N):
    ans -= A[i]**2
    ans %= mod

ans *= pow(2,mod-2,mod)
ans %= mod
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# C

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect
import itertools

input = sys.stdin.readline
mod = 10**9 + 7

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

N = int(input())
A = list(map(int, input().split()))

cumA = list(itertools.accumulate(A[::-1]))[::-1]
# print(A, cumA)

ans = 0
for i in range(len(A)-1):
    ans += (A[i] * cumA[i+1]) % mod

print(ans % mod)

Submission status: Accepted

Solution code:
def main():
    mod = 10**9 + 7
    n = int(input())
    a = [int(i) for i in input().split()]
    _s = sum(a)
    s = [_s - ai for ai in a]
    ans = 0
    for i in range(n):
        ans = ((a[i] * s[i]) % mod + ans) % mod
    print(ans * pow(2, mod - 2, mod) % mod)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(a) for a in input().split()]
print((sum(A) ** 2 - sum([a ** 2 for a in A])) // 2 % (10 ** 9 + 7))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
mod = 10**9 + 7

sum_a = 0
sum_ex = 0
for ai in a:
    sum_a += ai
    sum_a %= mod
    sum_ex += ai**2
    sum_ex %= mod

ans = (sum_a*sum_a - sum_ex)%mod
ans *= pow(2,mod-2,mod)
ans %= mod
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

MOD = 10**9 + 7
a_cs = [0] * (n + 1)
for i in range(n):
    a_cs[i + 1] = a_cs[i] + a[i]
    a_cs[i + 1] %= MOD

ans = sum(a_cs[i] * a[i] % MOD for i in range(n))
ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N = int(input())
A = list(map(int, input().split()))

MOD= 10 ** 9 + 7

acc = [0] * (N + 1)
for i in range(1, N + 1):
    acc[i] = acc[i - 1] + A[i - 1]

ans = 0
for i in range(N):
    now = (acc[N] - acc[i + 1]) % MOD
    ans += now * A[i]
    ans %= MOD
print(ans % MOD)

Submission status: Accepted

Solution code:
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb  # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
# If the element is already present in the list,

# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect

# If the element is already present in the list,
# the right most position where element has to be inserted is returned

# ==============================================================================================
# fast I/O region

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None


    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType


def iterative(f, stack=[]):
    def wrapped_func(*args, **kwargs):
        if stack: return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
                continue
            stack.pop()
            if not stack: break
            to = stack[-1].send(to)
        return to

    return wrapped_func


#### END ITERATE RECURSION ####

# ===============================================================================================
# some shortcuts

mod = 1000000007


def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())


def zerolist(n): return [0] * n

def nextline(): out("\n")  # as stdout.write always print sring.

def testcase(t):
    for p in range(t):
        solve()

def printlist(a):
    for p in range(0, len(a)):
        out(str(a[p]) + ' ')

def lcm(a, b): return (a * b) // gcd(a, b)

def power(x, y, p):
    res = 1  # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0):
        return 0
    while (y > 0):
        if ((y & 1) == 1):  # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1  # y = y/2
        x = (x * x) % p
    return res

def ncr(n, r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
    if (n <= 1): return False
    if (n <= 3): return True
    if (n % 2 == 0 or n % 3 == 0): return False
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i = i + 6
    return True


n=int(inp())
N=10**9 + 7
ar=lis()
k=sum(ar)%N
ans=0
for i in ar:
    ans=(ans+(i*(k-i+N)%N)%N)%N
print((ans*power(2,N-2,N))%N)

Submission status: Accepted

Solution code:
mod = 10**9 + 7

n = int(input())
arr = [int(j) for j in input().split()]

su = sum(arr)
ans = 0
for x in arr:
	ans += x*(su-x)
	ans %= mod
print(ans*pow(2, mod-2, mod) % mod)

Submission status: Accepted

Solution code:
def gya(n):
    return pow(n,pr-2,pr)
N=int(input())
A=list(map(int,input().split()))
pr=10**9+7
t=0
m=0
for i in A:
    t=(t+i)%pr
    m=(m+i**2)%pr
print(((t**2-m)*gya(2))%pr)