import java.util.*;
public class Main {
	Scanner sc = new Scanner(System.in);

	int n;
	int[] A;
	int m,cnt;
	int h;
	public ArrayList<Integer> G  = new ArrayList<Integer>();

	public void input() {
		n = sc.nextInt();
		A = new int[n];
		for(int i=0; i<n; i++) {A[i] = sc.nextInt();}
	}

	public void shellSort() {
		cnt = 0;
		m = 0;
		for(h =1; h<=n; h=h*3+1) {
			m++;
			G.add(h);
		}
		for(int i=m-1; i>=0; i--) {insertSort(G.get(i));}
	}

	public void insertSort(int g) {
		for(int i=g; i<n; i++) {
			int v = A[i];
			int j = i -g;
			while(j>=0 && A[j] > v) {
				A[j+g]  =A[j];
				j -= g;
				cnt++;
			}
			A[j+g] = v;
		}
	}

	public void output() {
		System.out.println(m);
		for(int i=G.size()-1; i>=0; i--) {
			if(i == 0) System.out.println( G.get(i) );
			else System.out.print(G.get(i)+" ");
		}
		System.out.println(cnt);
		for(int i=0; i<n; i++) System.out.println(A[i]);
		System.out.println();
	}

	public static void main(String[] args) {
		Main obj = new Main();
		obj.input();
		obj.shellSort();
		obj.output();
	}
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Shell Sort

Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])

A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.

Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:

$1 \leq m \leq 100$

$0 \leq G_i \leq n$

cnt does not exceed $\lceil n^{1.5}\rceil$

Input

In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.

Output

In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.

In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints

$1 \leq n \leq 1,000,000$

$0 \leq A_i \leq 10^9$

Sample Input 1

5
5
1
4
3
2

Sample Output 1

2
4 1
3
1
2
3
4
5

Sample Input 2

3
3
2
1

Sample Output 2

1
1
3
1
2
3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		int[] A = new int[N];
		for (int i = 0; i < N; i++) {
			A[i] = scan.nextInt();
		}
		shellSort(A, N);
		for (int i = 0; i < A.length; i++) {
			System.out.println(A[i]);
		}
		scan.close();
	}

	static int cnt = 0;

	public static void shellSort(int[] A, int N) {
		// G(n+1)=3G(n)+1 n=0,1,2,,,
		int max = (int) Math.ceil((N + 1) / 3.0);
		System.out.println(max);
		int[] G = new int[max];
		for (int i = 0; i < G.length; i++) {
			G[i] = 3 * i + 1;
		}

		for (int i = G.length - 1; i >= 0; i--) {
			// ??????
			System.out.print(G[i]);
			if (i != 0) {
				System.out.print(" ");
			} else {
				System.out.println();
			}
			insertionSort(A, N, G[i]);
		}
		System.out.println(cnt);
	}

	public static void insertionSort(int[] A, int N, int g) {

		for (int i = g; i < N; i++) {
			int v = A[i];
			int j = i - g;
			// ?????§???????????????????????°???????????????????????\????????????????????????????????§??????
			while (j >= 0 && A[j] > v) {
				A[j + g] = A[j];
				j -= g;
				cnt++;
			}
			A[j + g] = v;
		}
	}
}


import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		// TODO ?????????????????????????????????????????????
		new Main().start();
	}
	void start(){
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] a = new int[n];
		for(int i = 0; i < n; i++){
			a[i] = in.nextInt();
		}
		printArray(shellSort(a,n));

		in.close();
	}
	int cnt = 0;
	int[] insertionSort(int[]a, int n, int g){
		for(int i = g; i < n; i++){
			int v = a[i];
			int j = i - g;
			while(j >= 0 && a[j] > v){
				a[j+g] = a[j];
				j -= g;
				cnt++;
			}
			a[j+g] = v;
		}
		return a;
	}
	int[] shellSort(int[] a, int n){
		cnt = 0;
		int m = (int)(Math.log(n) / Math.log(4));
		int[] g = new int[m];
		for(int i = 0; i < m; i++){
			g[m-i-1] = (int)Math.pow(4, i);
		}
		for(int i = 0; i < m; i++){
			a = insertionSort(a,n,g[i]);
		}
		System.out.println(m);
		printArray2(g);
		System.out.println(cnt);
		return a;
	}
	void printArray(int[] a){
		for(int x : a){
			System.out.println(x);
		}
	}
	void printArray2(int[] a){
		System.out.print(a[0]);
		for(int i= 1; i < a.length; i++){
			System.out.print(" " + a[i]);
		}
		System.out.println();
	}

}


import java.util.Scanner;

public class Main {
  static int insertionSort(int[] a, int n, int g) {
    int t, j;
    int count = 0;
    for (int i = g; i < n; i++) {
      t = a[i];
      j = i - g;
      while (j >= 0 && a[j] > t) {
        a[j + g] = a[j];
        j -= g;
        count++;
      }
      a[j + g] = t;
    }
    return count;
  }

  static int shellSort(int[] a, int n) {
    int count = 0;
    int g = 0;
    int m = 0;
    for (int g_tmp = 1; g_tmp < n / 9; g_tmp += 3 * g_tmp + 1) {
      m++;
      g = g_tmp;
    }
    if (n < 10) {
      m = 1;
      g = 1;
    }
    System.out.println(m);
    int[] G = new int[m];
    G[0] = g;
    for (int i = 1; i < m; i++) {
      G[i] = (G[i - 1] - 1) / 3;
    }
    for (int i = 0; i < m; i++)
      count += insertionSort(a, n, G[i]);
    for (int i = 0; i < m; i++) {
      System.out.print(G[i]);
      if (i != m - 1) System.out.print(' ');
      else System.out.println();
    }
    return count;
  }

  public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    int n = stdIn.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++) a[i] = stdIn.nextInt();
    int count = shellSort(a, n);
    System.out.println(count);
    for (int i = 0; i < n; i++)
      System.out.println(a[i]);
  }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main{
	public static void main(String[] args)
	{
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			int n = Integer.parseInt(br.readLine());
			int[] A = new int[n];
			for(int i = 0; i<n ; i++)
			{
				A[i] = Integer.parseInt(br.readLine());
			}
			shellSort(A,n);

		}catch(IOException e){
			e.printStackTrace();
		}
	}
	public static void shellSort(int[] arr , int l)
	{
		StringBuilder sb = new StringBuilder();
		int m = 1 ,cnt =0;
		int G[] = new int[13];
		G[0] = 1;
		while((G[m] = G[m-1] * 3 +1) <= l){
			m++;
		}
		sb.append(m).append('\n');
		m--;
		for(; m >= 0 ; m--){
			sb.append(G[m]).append(' ');
			cnt += insertionSort(arr,l,G[m]);
		}
		sb.deleteCharAt(sb.length()-1).append('\n').append(cnt).append('\n');

		for(m = 0 ; m < l ; m++){
			sb.append(arr[m]).append('\n');
		}
			System.out.print(sb.toString());
	}
	public static int insertionSort(int[] a,int n , int g)
	{
		int cnt = 0;
		int v;
		for(int i = g ; i < n ; i++)
		{
			v = a[i];
			int j = i-g;
			while(j >= 0 && a[j] > v)
			{
				a[j+g] = a[j];
				a[j] = v;
				j -= g;
				cnt++;
			}
		}
		return cnt;
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		int n = scanner.nextInt();
		int[] a = new int[n];

		for (int i = 0; i < n; i++) {
			a[i] = scanner.nextInt();
		}

		scanner.close();

		int cnt = 0;

		int m;
		for (m = 0; (n >> m) > 0; m++);
		int[] g = new int[m];
		for (int i = 0; i < m; g[i] = (1 << (m - i - 1)), i++);

		for (int k = 0; k < m; k++) {
			for (int i = g[k]; i < n; i++) {
				int v = a[i];
				int j = i - g[k];

				while (j >= 0 && a[j] > v) {
					a[j + g[k]] = a[j];
					j -= g[k];
					cnt ++;
				}
				a[j + g[k]] = v;
			}
		}

		System.out.println(m);
		for (int i = 0; i < m - 1; i++) {
			System.out.print(g[i] + " ");
		}
		System.out.println(g[m - 1]);

		System.out.println(cnt);

		for (int i = 0; i < n; i++) {
			System.out.println(a[i]);
		}
	}
}


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
	public static void init(int[] arr, int[] init) {
		for(int i = 0; i < arr.length; i++) {
			arr[i] = init[i];
		}
	}
	public static int insertionSort(int[] arr, int n, int g) {
		int count = 0;
		for(int i = g; i < n; i++) {
			int key = arr[i];
			int j = i - g;
			while(j >= 0 && arr[j] > key) {
				arr[j + g] = arr[j];
				j -= g;
				count++;
			}
			arr[j + g] = key;
		}
		return count;

	}
	public static int shellSort(int[] arr, int n, List<Integer> list) {
		int count = 0;
		for(int i = 0; i < list.size(); i++) {
			count += insertionSort(arr, n, list.get(i));
		}
		return count;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] arr = new int[n];
		int[] init = new int[n];
		int count = 0;
		List<Integer> g = new ArrayList<>();
		for(int i = 0; i < n; i++) {
			init[i] = sc.nextInt();
			arr[i] = init[i];
		}
		int index = 1;
		g.add(index);
		if(n > 4) {
			index = 4;
			g.add(0, index);
		}
		while(index <= n / 9) {
			if(index == 4) {
				index = index * 3 + 1;
				continue;
			}
			g.add(0, index);
			index = index * 3 + 1;
		}
		while (true) {
			count = shellSort(arr, n, g);
			if(count < Math.ceil(Math.pow(n, 1.5))) {
				break;
			} else {
				init(arr, init);
				count = 0;
				index = 3 * index + 1;
				g.add(0, index);
			}
		}
		System.out.println(g.size());
		for(int i = 0; i < g.size(); i++) {
			if(i == g.size() - 1) {
				System.out.println(g.get(i));
			} else {
				System.out.print(g.get(i) + " ");
			}
		}
		System.out.println(count);
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);

		}
		sc.close();
	}
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	private static int cnt;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int[] data = new int[n];

    	for (int i = 0; i < n; i++) {
    		data[i] = sc.nextInt();
    	}

    	// Shell Sort
    	cnt = 0;
    	int[] g;

//    	int m = (n - 1) / 3 + 1;
//    	if (m > 100) {
//    		m = 100;
//    	}
//    	g = new int[m];
//    	for (int i = m - 1; i >= 0; i --) {
//    		g[i] = 3 * i + 1;
//    	}

    	int m = (int)Math.pow(n, 1.25);
    	if (m > 100) {
    		m = 100;
    	}
		g = new int[m];
		int ii = 0;
		g[ii] = 1;
		for (ii = 1; ii < m; ii++) {
			int next = g[ii - 1] * 3 + 1;
			if (next > n) {
				break;
			}
			g[ii] = next;
		}
		m = ii;

    	for (int i = 0; i < m; i++) {
    		insertionSort(data, n, g[m - 1 - i]);
    	}

    	// m
    	System.out.println(m);
    	// g
		StringBuffer printData = new StringBuffer();
		for (int i = 0; i < m; i++) {
			printData.append(g[m - 1 - i]);
			printData.append(" ");
		}
		printData.delete(printData.length() - 1, printData.length());
		System.out.println(printData);
    	// cnt
    	System.out.println(cnt);
    	// data
		for (int i = 0; i < data.length; i++) {
	    	System.out.println(data[i]);
		}

    	sc.close();
	}

	private static void insertionSort(int[] data, int n, int g) {
		for (int i = g; i < n; i++) {
			int v = data[i];
			int j = i - g;
			int tmp;
//			for (; j >= 0 && data[j] > v;) {
//			    data[j + g] = data[j];
			for (; j >= 0 && (tmp = data[j]) > v;) {
				data[j + g] = tmp;
				j -= g;
				cnt++;
			}
			data[j + g] = v;
		}
		return;
	}
}


import java.util.*;

class Main {
    public static void main(String...args) {
        Scanner scan = new Scanner(System.in);
        int aryLen = scan.nextInt();
        int[] ary = new int[aryLen];
        int interCount = 1;
        int sortCount = 0;
        int maxInter = 0;

        for(int i = 0; i < aryLen; i++) {
            ary[i] = scan.nextInt();
        }

        int inter = 1;
        while(inter * 3 + 1 < aryLen ) {
            inter = inter * 3 + 1;
            interCount++;
        }

        maxInter = inter;

        for(; inter > 0 ; inter /= 3) {
            for(int j = inter; j < aryLen; j++) {
                int tmp = ary[j];
                int point = j;
                while(point - inter >= 0 && ary[point - inter] > tmp) {
                    ary[point] = ary[point - inter];
                    point -= inter;
                    sortCount++;
                }
                ary[point] = tmp;
            }

        }
        System.out.println(interCount);
        for(; maxInter > 0; maxInter/=3) {
            System.out.print(maxInter);
            if(maxInter != 1) {
                System.out.print(" ");
            } else if(maxInter == 1) {
                System.out.println();
            }
        }
        System.out.println(sortCount);
        for(int k = 0; k < aryLen; k++) {
            System.out.println(ary[k]);
        }
    }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}
		shellSort(a, n);
		printArrays(a, n);
	}

	public static int insertionSort(int a[], int n, int g) {
		int v, j = 0, cnt = 0;
		for (int i = g; i < n; i++) {
			v = a[i];
			j = i - g;
			while (j >= 0 && a[j] > v) {
				a[j + g] = a[j];
				j = j - g;
				cnt++;
			}
			a[j + g] = v;
		}
		return cnt;
	}

	public static void shellSort(int a[], int n) {
		int cnt = 0;
		ArrayList<Integer> b = new ArrayList<>();
		for (int h = 1;;) {
			if (h > n)
				break;
			b.add(h);
			h = 3 * h + 1;
		}
		int m = b.size();
		System.out.println(m);
		for (int i = m-1; i >0; i--) {
			System.out.print(b.get(i) + " ");
		}
		System.out.println(b.get(0));

		for (int i = m - 1; i >= 0; i--) {
			cnt += insertionSort(a, n, b.get(i));
		}
		System.out.println(cnt);
	}

	public static void printArrays(int a[], int n) {
		for (int i = 0; i < n; i++) {
			System.out.println(a[i]);
		}
	}
}


import java.util.*;

class Main{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		HashSet<Long> hs = new HashSet<Long>();
		String cmd, str;
		long hc;

		for(int i=0; i<n; i++){
			cmd = sc.next();
			str = sc.next();
			hc = str.hashCode();
			if(cmd.equals("insert")){
				hs.add(hc);
			} else if(cmd.equals("find")){
				if(hs.contains(hc)) System.out.println("yes");
				else                System.out.println("no");
			}
		}
	}
}

Search III

Your task is to write a program of a simple dictionary which implements the following instructions:

insert str: insert a string str in to the dictionary

find str: if the distionary contains str, then print 'yes', otherwise print 'no'

Input

In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.

Output

Print yes or no for each find instruction in a line.

Constraints

A string consists of 'A', 'C', 'G', or 'T'

1 ≤ length of a string ≤ 12

n ≤ 1000000

Sample Input 1

5
insert A
insert T
insert C
find G
find A

Sample Output 1

no
yes

Sample Input 2

13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T

Sample Output 2

yes
no
no
yes
yes
yes

Notes

Template in C


import java.util.Scanner;

public class Main{

	// 要素数は素数を設定
	public static String[] hashTable = new String[50001];

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);
		int cnt = new Integer(s.nextLine()).intValue();
		for(int i=0 ; i<cnt ; i++) {
			String[] inputData = s.nextLine().split(" ");
			if("insert".equals(inputData[0])) {
				insert(inputData[1]);
			}else {
				find(inputData[1]);
			}
		}
	}

	public static void insert(String value) {
		int hashValue = hashFunction(value);
		// 衝突しない場合、そのまま配列に格納する
		if(hashTable[hashValue] == null || hashTable[hashValue] == "") {
			hashTable[hashValue] = value;
		}
		// 衝突する場合、ハッシュコードに「衝突回数*3」を加算して再ハッシュする
		else {
			aaa :for(int i=1 ; ; i++) {
				hashValue += 1;
				int reHash = hashValue % 50001;
				// リハッシュした場所に格納できる場合、格納して処理を抜ける
				if(hashTable[reHash] == null || hashTable[reHash] == "") {
					hashTable[reHash] = value;
					break aaa;
				}else if(value.equals(hashTable[reHash]))
					break aaa;
				else if(i == 101)
					break aaa;
			}
		}
	}

	public static void find(String value) {
		int hashValue = hashFunction(value);
		if(value.equals(hashTable[hashValue])) {
			System.out.println("yes");
		}else {
			bbb :for(int i=1 ; ; i++) {
				hashValue += 1;
				int reHash = hashValue % 50001;
				if(value.equals(hashTable[reHash])) {
					System.out.println("yes");
					break bbb;
				}
				if(hashTable[reHash] == null) {
					System.out.println("no");
					break bbb;
				}
			}
		}
	}

	public static int hashFunction(String value) {
		int v = 0;
		int p = 5;
		for(int i=0 ; i<value.length() ; i++) {
			if("A".equals(value.substring(i, i+1))) {
				v += 3 * p;
			}else if("C".equals(value.substring(i, i+1))) {
				v += 4 * p;
			}else if("G".equals(value.substring(i, i+1))) {
				v += 5 * p;
			}else if("T".equals(value.substring(i, i+1))) {
				v += 6 * p;
			}
			p *= 5;
		}
		return v % 50001;
	}
}


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {
	public static void main(String[] args) throws IOException {
		ContestScanner scan = new ContestScanner();
		final int n = scan.nextInt();
		final Dictionary dic = new Dictionary(200000000, (size, key) -> {
			int index = 0;

			for(int i=0, l=key.length(); i < l; i++)
			{
				index = index * 37 + (int)key.charAt(i);
				index = index % size;
			}
			return index;
		});
		(new Solve(n, scan.nextObjectArray(new ICommand[n], (scanner) -> {
			String name = scanner.next();
			return name.equals("insert") ? new InsertCommand(dic, scan.next()) : name.equals("find") ? new FindCommand(dic, scan.next()) : null;
		}))).solve();
	}
}
class Solve {
	private final int n;
	private final ICommand[] commands;

	public Solve(final int n, final ICommand[] commands)
	{
		this.n = n;
		this.commands = commands;
	}

	public void solve()
	{
		for(ICommand c: commands)
		{
			c.run();
		}
	}
}
interface ICommand {
	public void run();
}
class InsertCommand implements ICommand {
	public final String key;
	public final Dictionary dic;
	public InsertCommand(Dictionary dic, String key)
	{
		this.dic = dic;
		this.key = key;
	}
	public void run()
	{
		dic.add(key);
	}
}
class FindCommand implements ICommand {
	public final String key;
	public final Dictionary dic;
	public FindCommand(Dictionary dic, String key)
	{
		this.dic = dic;
		this.key = key;
	}
	public void run()
	{
		System.out.println((dic.find(key) ? "yes" : "no"));
	}
}
class ListItem {
	public final String value;
	public ListItem next;

	public ListItem(String value)
	{
		this.value = value;
		this.next = null;
	}

	public ListItem add(String value)
	{

		ListItem entry = this;

		while(entry != null && !entry.value.equals(value)) entry = entry.next;

		if(entry != null) return this;

		entry = new ListItem(value);
		entry.next = this;
		return entry;
	}
}
interface HashCreator {
	public int hash(int size, String value);
}
class Dictionary {
	private final ListItem[] table;
	private final int tableSize;
	private final HashCreator hashCreator;

	public Dictionary(final int size, final HashCreator hashCreator)
	{
		this.tableSize = size;
		this.table = new ListItem[size];
		this.hashCreator = hashCreator;
	}

	public void add(String value)
	{
		int index = hashCreator.hash(tableSize, value);
		ListItem entry = table[index];
		if(entry == null) table[index] = new ListItem(value);
		else table[index] = entry.add(value);
	}

	public boolean find(String value)
	{
		int index = hashCreator.hash(tableSize, value);
		ListItem entry = table[index];

		while(entry != null &&  !entry.value.equals(value))
		{
			entry = entry.next;
		}

		return entry != null;
	}
}
class ContestScanner {
	BufferedReader reader;
	String[] line;
	int index;
	public ContestScanner() {
		reader = new BufferedReader(new InputStreamReader(System.in));
	}

	public ContestScanner(String filename) throws FileNotFoundException {
		reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
	}

	public static interface ICreator<T> {
		public T createFromToken(final ContestScanner scanner) throws IOException;
	}

	public static interface IArrayInitializer {
		public void initialize(final ContestScanner scanner, final int i) throws IOException;
	}

	public static interface IObjectInitializer<T> {
		public T initialValue(final ContestScanner scanner);
	}

	public static class ObjectArrayInitializer<T> implements IArrayInitializer {
		protected T[] arr;
		protected final IObjectInitializer<T> initializer;

		private ObjectArrayInitializer(T[] arr, final IObjectInitializer<T> initializer)
		{
			this.arr = arr;
			this.initializer = initializer;
		}

		public static <T> ObjectArrayInitializer<T> create(T[] arr, final IObjectInitializer<T> initializer)
		{
			return new ObjectArrayInitializer<T>(arr, initializer);
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = initializer.initialValue(scanner);
		}

		public T[] getArray()
		{
			return this.arr;
		}
	}

	public static class ByteArrayInitializer implements IArrayInitializer {
		protected byte[] arr;

		private ByteArrayInitializer(final int n)
		{
			this.arr = new byte[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextByte();
		}

		public byte[] getArray()
		{
			return this.arr;
		}
	}

	public static class ShortArrayInitializer implements IArrayInitializer {
		protected short[] arr;

		private ShortArrayInitializer(final int n)
		{
			this.arr = new short[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextShort();
		}

		public short[] getArray()
		{
			return this.arr;
		}
	}

	public static class IntArrayInitializer implements IArrayInitializer {
		protected int[] arr;

		private IntArrayInitializer(final int n)
		{
			this.arr = new int[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextInt();
		}

		public int[] getArray()
		{
			return this.arr;
		}
	}

	public static class LongArrayInitializer implements IArrayInitializer {
		protected long[] arr;

		private LongArrayInitializer(final int n)
		{
			this.arr = new long[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextLong();
		}

		public long[] getArray()
		{
			return this.arr;
		}
	}

	public static class FloatArrayInitializer implements IArrayInitializer {
		protected float[] arr;

		private FloatArrayInitializer(final int n)
		{
			this.arr = new float[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextFloat();
		}

		public float[] getArray()
		{
			return this.arr;
		}
	}

	public static class DoubleArrayInitializer implements IArrayInitializer {
		protected double[] arr;

		private DoubleArrayInitializer(final int n)
		{
			this.arr = new double[n];
		}

		public void initialize(final ContestScanner scanner, final int i) throws IOException {
			this.arr[i] = scanner.nextDouble();
		}

		public double[] getArray()
		{
			return this.arr;
		}
	}

	public String nextToken() throws IOException {
		if(line == null || index >= line.length)
		{
			line = reader.readLine().trim().split(" ");
			index = 0;
		}

		return line[index++];
	}

	public String next() throws IOException {
		return nextToken();
	}

	public String readLine() throws IOException {
		line = null;
		index = 0;

		return reader.readLine();
	}

	public byte nextByte() throws IOException, NumberFormatException {
		return Byte.parseByte(nextToken());
	}

	public short nextShort() throws IOException, NumberFormatException {
		return Short.parseShort(nextToken());
	}

	public int nextInt() throws IOException, NumberFormatException {
		return Integer.parseInt(nextToken());
	}

	public long nextLong() throws IOException, NumberFormatException {
		return Long.parseLong(nextToken());
	}

	public float nextFloat() throws IOException, NumberFormatException {
		return Float.parseFloat(nextToken());
	}

	public double nextDouble() throws IOException, NumberFormatException {
		return Double.parseDouble(nextToken());
	}

	public <T> T nextObject(final ICreator<T> creator) throws IOException, NumberFormatException {
		return creator.createFromToken(this);
	}

	public int[] nextIntArray(final int N) throws IOException, NumberFormatException {
		int[] result = new int[N];

		for(int i=0; i < N; i++) result[i] = nextInt();

		return result;
	}

	public long[] nextLongArray(final int N) throws IOException, NumberFormatException {
		long[] result = new long[N];

		for(int i=0; i < N; i++) result[i] = nextLong();

		return result;
	}

	public float[] nexFloatArray(final int N) throws IOException, NumberFormatException {
		float[] result = new float[N];

		for(int i=0; i < N; i++) result[i] = nextFloat();

		return result;
	}

	public double[] nexDoubleArray(final int N) throws IOException, NumberFormatException {
		double[] result = new double[N];

		for(int i=0; i < N; i++) result[i] = nextDouble();

		return result;
	}

	public <T> T[] nextObjectArray(T[] result, final ICreator<T> creator) throws IOException, NumberFormatException {
		for(int i=0, N=result.length; i < N; i++) result[i] = nextObject(creator);

		return result;
	}

	public <T> ArrayList<T> nextGenericObjectArrayList(final int N, final ICreator<T> creator) throws IOException, NumberFormatException {
		ArrayList<T> result = new ArrayList<T>();
		for(int i=0; i < N; i++) result.add(nextObject(creator));

		return result;
	}

	public void nextTable(final int N, IArrayInitializer... arrayInitializers) throws IOException, NumberFormatException {
		for(int i=0; i < N; i++) for(IArrayInitializer initializer: arrayInitializers)
		{
			initializer.initialize(this, i);
		}
	}
}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ArrayList<String> array = new ArrayList<String>();

        int N = in.nextInt();
        for (int i = 0; i < N; i++){
            String c1 = in.next();
            String c2 = in.next();

            if (c1.equals("insert")){
                array.add(c2);
            }else if(c1.equals("find")){
                if (array.contains(c2)){
                    System.out.println("yes");
                }else{
                    System.out.println("no");
                }
            }

            System.out.println(c2);
        }
    }
}


import java.util.Scanner;

public class Main {

	static int count = 0;

	public static void main(String[] args) throws Exception {

		Scanner sc = new Scanner(System.in);
		int n  = sc.nextInt();

		String[] strArray = new String[n];
		int end = 0;
		StringBuffer sb = new StringBuffer();

		for(int i = 0; i < n; i++) {
			String order = sc.next();
			String str = sc.next();

			if(order.equals("insert")) {
				strArray[end] = str;
				end++;
			} else {
				boolean chk = false;

				for(int j = 0; j < end; j++) {
					if(str.equals(strArray[j])) {
						chk = true;
						break;
					}
				}
				if(chk) {
					sb.append("yes\n");
				} else {
					sb.append("no\n");
				}
			}
		}
		System.out.println(sb);
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;

class Main {
	public static void main(String args[]) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		try {
			int ope_num = Integer.parseInt(br.readLine());
			Dictionary(ope_num,br);
		} catch (NumberFormatException | IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}

	//enum宣言
	public static enum Operate{
		insert("insert"),
		find ("find"),;

		private final String name;

		Operate(String name){
			this.name = name;
		}

		String getName(){
			return this.name;
		}

		public static Operate getEnumName(String str){
			for(Operate v : values()){
				if(v.getName().equals(str)){
					return v;
				}
			}
			throw new IllegalArgumentException("undefined : " + str);
		}
	}

	public static void Dictionary( int ope_num ,BufferedReader br ){
		ArrayDeque<String> que = new ArrayDeque<String>();
		int i;
		String[] op;
		boolean bfind = false;

		for ( i = 0; i < ope_num; i++) {
			try {
				op = br.readLine().split(" ");		//キーと命令を分割

				switch( Operate.getEnumName(op[0]) ){ //命令によって処理
				case insert:
					que.addFirst(op[1]);			//キューに追加
					break;
				case find:
					bfind = que.contains(op[1]);				//キューから削除

					if(bfind) {
						System.out.println("yes");
						bfind = false;
					}else {
						System.out.println("no");
					}

					break;
				}
			} catch (IOException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		}
	}
}


import java.util.HashSet;
import java.util.Set;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        Set<String> dic = new HashSet<String>();

        String cmd;
        String str;
        int times = sc.nextInt();

        for(int i = 0; i < times; i++){
            cmd = sc.next();
            str = sc.next();

            if(cmd.equals("insert"))
                dic.add(str);

            if(cmd.equals("find")){
                if(dic.contains(str))
                    System.out.println("yes");
                else
                    System.out.println("no");
            }
        }
        sc.close();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileStore;

public class Main {

  public static void main(String[] args) throws IOException {

    try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

      int n = Integer.parseInt(br.readLine());
      String[] order;
      StringBuilder result = new StringBuilder(n*4);
      Dictionary dict = new Dictionary(4, n);

      for(int i=0; i<n; i++) {
        order = br.readLine().split(" ");
        switch( order[0] ) {
          case "insert" :
            dict.insert(order[1]);
            break;
          case "find" :
            result.append( dict.find(order[1]) ).append("\n");
            break;
        }
      }

      System.out.print(result);
    }
  }
}

class Dictionary {
  String[][] dict2d;
  int[] pos;

  public Dictionary(int first, int second) {
    dict2d = new String[first][second];
    pos = new int[first];
  }

  public void insert(String str) {
    switch(str.substring(0,1)) {
      case "A" :
        dict2d[0][pos[0]++] = str;
        break;
      case "C" :
        dict2d[1][pos[1]++] = str;
        break;
      case "G" :
        dict2d[2][pos[2]++] = str;
        break;
      case "T" :
        dict2d[3][pos[3]++] = str;
        break;
    }
  }
  public String find(String ref) {
    boolean result = false;
    switch(ref.substring(0,1)) {
      case "A" :
        result = isExistSeachBylinear(0, ref);
        break;
      case "C" :
        result = isExistSeachBylinear(1, ref);
        break;
      case "G" :
        result = isExistSeachBylinear(2, ref);
        break;
      case "T" :
        result = isExistSeachBylinear(3, ref);
        break;
    }

    return result ? "yes" : "no";
  }
  private boolean isExistSeachBylinear(int first, String ref) {

    for (int i=0; i<pos[first]; i++) {
      if(ref.length() == dict2d[first][i].length())
        if(ref.equals(dict2d[first][i])) return true;
    }

    return false;
  }
}


import java.util.Scanner;
import java.util.HashSet;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        HashSet<String> set = new HashSet<String>();

        String x,y;
        int n = sc.nextInt();
        int i;

        for(i = 0;i < n;i++){
            x = sc.next();
            y = sc.next();

            if(x.equals("insert")){
                set.add(y);
            }

            if(x.equals("find")){
                if(set.contains(y)){
                    System.out.printf("yes\n");
                }else{
                    System.out.printf("no\n");
                }
            }
        }
    }
}


import java.util.*;

public class Main {

    static int NOT_FOUND = 99999999;
    static int M = 1046527;

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Integer[] intArr = new Integer[M];
        for (int i = 0; i < n; i++) {
            String command = sc.next();
            String value = sc.next();
            if (command.equals("insert")) {
                insert(intArr, toInt(value));
            } else {
                if (search(intArr, toInt(value)).equals(NOT_FOUND)) {
                    System.out.println("no");
                } else {
                    System.out.println("yes");
                }
            }

        }
    }

    static int getChar(char ch) {
        if (ch == 'A') {
            return 1;
        } else if (ch == 'C') {
            return 2;
        } else if (ch == 'G') {
            return 3;
        } else if (ch == 'T') {
            return 4;
        } else {
            return 0;
        }
    }

    static int toInt(String s) {
        int sum = 0;
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            sum += Math.pow(5, i) * getChar(arr[i]);
        }
        return sum;
    }

    static int h1(int key) {
        return key % M;
    }

    static int h2(int key) {
        return 1 + (key % (M - 1));
    }

    static int h(int key, int i) {
        return (h1(key) + i * h2(key)) % M;
    }

    static int insert(Integer[] arr, int key) {
        int i = 0;
        while (true) {
            int j = h(key, i);
            if (arr[j] == null) {
                arr[j] = key;
                return j;
            } else {
                i++;
            }
        }
    }

    static Integer search(Integer[] arr, int key) {
        int i = 0;
        while (true) {
            int j = h(key, i);
            if (arr[j] == null || i >= M) {
                return NOT_FOUND;
            } else if (key == arr[j]) {
                return j;
            } else {
                i++;
            }
        }
    }

}


import java.util.Scanner;

public class Main{
	public static int M = 1046527;
	public static char H[][] = new char[M][14];
	public static char x[] = new char[14];
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		String cmd, s;
		for(int i = 0; i < N; i++) {
			char []str = new char[14];
			cmd = scan.next();
			s = scan.next();
			for(int j = 0; j < s.length(); j++) {
				str[j] = s.charAt(j);
			}
			if(cmd.charAt(0) == 'i') {
				insert(str);
			}else {
				if(find(str) == 1) {
					System.out.println("yes");
				}else {
					System.out.println("no");
				}
			}
		}
		scan.close();
	}

	public static int getChar(char ch) {
		if(ch == 'A') return 1;
		else if(ch == 'C') return 2;
		else if(ch == 'G') return 3;
		else if(ch == 'T') return 4;
		else return 0;
	}

	public static long getKey(char []str) {
		long sum = 0;
		long p = 1;
		for(int i = 0; i < 14; i++) {
			sum += p * (getChar(str[i]));
			p *= 5;
		}
		return sum;
	}

	public static int find(char []str) {
		long key = getKey(str);
		int h;
		for(int i = 0;; i++) {
			h = (h1(key) + i * h2(key)) % M;

			if(isCheck(H[h], str)) return 1;
			else if(H[h][0]== x[0]) return 0;
		}
	}
	public static boolean isCheck(char[] c1, char[] c2) {
		for(int i = 0; i < 14; i++) {
			if(c1[i] != c2[i]) {
				return false;
			}
		}
		return true;
	}
	public static void strcpy(char[] c1, char[] c2) {
		for(int i = 0; i < 14; i++) {
			c1[i] = c2[i];
		}
	}
	public static int insert(char str[]) {

		long key = getKey(str);
		int h;
		for(int i = 0;; i++) {
			h = (h1(key) + i * h2(key)) % M;
			if(isCheck(H[h], str)) return 1;
			else if(H[h][0]== x[0]) {
				strcpy(H[h], str);
				return 0;
			}
		}
	}
	public static int h1(long key) {
		return (int)(key % M);
	}
	public static int h2(long key) {
		return (int)(key % (M - 1));
	}
	public static void disp(char []c) {
		for(int i = 0; i < 14; i++) {
			System.out.print(c[i]);
		}
		System.out.println();
	}
}


import java.util.*;

/**
 * C Main
 *
 * @date 2020.09.19
 * @author 焼き鮭 <yaki-shake@up-tri.me>
 */

public class Main {
  Scanner sc;
  long MOD = 1000000007;

  public static void main(String[] args) {
    new Main().execute();
  }

  public void execute() {
    this.sc = new Scanner(System.in);

    int n = sc.nextInt();
    int[] ax = new int[n];
    for (int i = 0; i < n; i++) {
      ax[i] = sc.nextInt();
    }

    long prod = 1;
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        prod = (prod + (ax[i] % MOD * ax[j] % MOD)) % MOD;
      }
    }

    System.out.println(prod);
  }
}

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


import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.*;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.pow;

import static java.lang.String.format;

public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner();
        final int n = scanner.nextInt();
        final long[] a = new long[n];
        for (int i =0 ; i < n; i++) {
            a[i] = scanner.nextLong();
        }
        long sumA = LongStream.of(a).sum();
        BigInteger bi = BigInteger.valueOf(sumA);
        System.out.println(bi.multiply(bi).subtract(Arrays.stream(a).mapToObj(BigInteger::valueOf).map(it -> it.multiply(it)).reduce(BigInteger.ZERO, (x, b) -> x.add(b))).divide(BigInteger.valueOf(2)).mod(BigInteger.valueOf(1000_000_007)).longValue());

    }

    public static int upper_bound(int[] a,int val){
        return upper_bound(a,0,a.length,val);
    }
    public static int upper_bound(int[] a,int l,int r,int val){
        if(r-l==1){
            if(a[l]>val) return l;
            return r;
        }
        int mid=(l+r)/2;
        if(a[mid]>val){
            return upper_bound(a,l,mid,val);
        }else{
            return upper_bound(a,mid,r,val);
        }
    }
    public static <T> int upper_bound(T[] a,int l,int r,T val,Comparator<T> comparator){
        if(r-l==1){
            if(comparator.compare(a[l],val)>0) return l;
            return r;
        }
        int mid=(l+r)/2;
        if(comparator.compare(a[mid],val)>0){
            return upper_bound(a,l,mid,val,comparator);
        }else{
            return upper_bound(a,mid,r,val,comparator);
        }
    }
    public static int lower_bound(int[] a,int val){
        return lower_bound(a,0,a.length,val);
    }
    public static int lower_bound(int[] a,int l,int r,int val){
        if(r-l==1){
            if(a[l]<val) return r;
            return l;
        }
        int mid=(l+r)/2;
        if(a[mid]<val){
            return lower_bound(a,mid,r,val);
        }else{
            return lower_bound(a,l,mid,val);
        }

    }

    public static <T> int lower_bound(T[] a,int l,int r,T val,Comparator<T> comparator){
        if(r-l==1){
            if(comparator.compare(a[l],val)<0) return r;
            return l;
        }
        int mid=(l+r)/2;
        if(comparator.compare(a[mid],val)<0){
            return lower_bound(a,mid,r,val,comparator);
        }else{
            return lower_bound(a,l,mid,val,comparator);
        }
    }

    public static void print(Object object){
        System.out.print(object);
    }
    public static void put(Object object) {
        System.out.println(object);
    }
    public static void put(){
        System.out.println();
    }

    final static private class Scanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;

        private boolean hasNextByte() {
            if (ptr < buflen) {
                return true;
            } else {
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (buflen <= 0) {
                    return false;
                }
            }
            return true;
        }

        private int readByte() {
            if (hasNextByte())
                return buffer[ptr++];
            else
                return -1;
        }

        private boolean isPrintableChar(int c) {
            return 33 <= c && c <= 126;
        }

        public boolean hasNext() {
            while (hasNextByte() && !isPrintableChar(buffer[ptr]))
                ptr++;
            return hasNextByte();
        }

        public String next() {
            if (!hasNext())
                throw new NoSuchElementException();
            StringBuilder sb = new StringBuilder();
            int b = readByte();
            while (isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }

        public long nextLong() {
            if (!hasNext())
                throw new NoSuchElementException();
            long n = 0;
            boolean minus = false;
            int b = readByte();
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            if (b < '0' || '9' < b) {
                throw new NumberFormatException();
            }
            while (true) {
                if ('0' <= b && b <= '9') {
                    n *= 10;
                    n += b - '0';
                } else if (b == -1 || !isPrintableChar(b)) {
                    return minus ? -n : n;
                } else {
                    throw new NumberFormatException();
                }
                b = readByte();
            }
        }

        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
                throw new NumberFormatException();
            return (int) nl;
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }
    final static private class FixedPair {
        final private long x, y;
        final static public FixedPair ZEROS=new FixedPair(0,0);
        FixedPair(long x, long y) {
            this.x = x;
            this.y = y;
        }

        public long getX() {
            return x;
        }

        public long getY() {
            return y;
        }

        @Override
        public int hashCode() {
            return (int)x+(int)y;
        }

        @Override
        public boolean equals(Object obj) {
            boolean result=super.equals(obj);
            if(obj.getClass()!=this.getClass()){
                return false;
            }
            FixedPair pair=(FixedPair)obj;
            if(this.x==pair.x&&this.y==pair.y) return true;
            return false;
        }

        @Override
        public String toString() {
            return String.format("(%d,%d)", x, y);
        }
    }
    final static private class Tuple<T,V>{
        //immutabl1でないことに注意(T,Vがmutableの場合変更可能)
        final private T t;
        final private V v;
        Tuple(T t,V v){
            this.t=t;
            this.v=v;
        }

        public T getT() {
            return t;
        }

        public V getV() {
            return v;
        }

        @Override
        public int hashCode() {
            return (t.hashCode()+v.hashCode());
        }

        @Override
        @SuppressWarnings("unchecked")
        public boolean equals(Object obj) {
            if(obj.getClass()!=this.getClass()){
                return false;
            }
            Tuple<T,V> tuple=(Tuple<T, V>) obj;
            return tuple.t.equals(this.t)&&tuple.v.equals(this.v);
        }

        @Override
        public String toString() {
            return String.format("<Tuple>=<%s,%s>",t,v);
        }
    }
    final static private class Util {
        static long gcd(long a,long b){
            //最大公約数
            if(a%b==0)return b;
            return gcd(b,a%b);
        }
        static long lcm(long a,long b){
            //最小公倍数
            long gcd=gcd(a,b);
            long result=b/gcd;
            return a*result;
        }
        static long kaijoMod(int n,int mod){
            if(n<1) return -1;
            long result=1;
            for(int i=n;i>1;i--){
                result*=i;
                result%=mod;
            }
            return result;
        }
        static <T extends Comparable<T>> Map<T,Integer> count(List<T> list){
            //副作用
            Collections.sort(list);
            Map<T,Integer> result=new HashMap<>();
            int l=0,r=0;
            while(l<list.size()){
                while(r<list.size()-1&&list.get(r).equals(r+1)){
                    r++;
                }
                result.put(list.get(r),r-l+1);
                r++;
                l=r;
            }
            return result;

        }
        static Map<Integer,Integer> count(int[] array){
            //副作用
            Arrays.sort(array);
            Map<Integer,Integer> result=new HashMap<>();
            int l=0,r=0;
            while(l<array.length){
                while(r<array.length-1&&array[r]==array[r+1]){
                    r++;
                }
                result.put(array[l],r-l+1);
                r++;
                l=r;
            }
            return result;
        }
        static <T> String toStringBWS(Iterable<T> iterable){
            Iterator<T> ite=iterable.iterator();
            return toStringBWS(ite);
        }
        static <T> String toStringBWS(Iterator<T> ite){
            StringBuilder sb=new StringBuilder();
            sb.append(ite.next());
            while(ite.hasNext()){
                sb.append(" ");
                sb.append(ite.next());
            }
            return sb.toString();
        }
        static int[] factoringInPrimeNumbers(long n,int size){
            //素因数分解
            //sizeがnに比べて小さい場合完全に素因数分解出来ていない可能性がある
            int[] result=new int[size];
            for(int i=2;n>1&&i< result.length;i++){
                while(n%i==0){
                    result[i]++;
                    n/=i;
                }
            }
            return result;

        }
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner(System.in)) {
            final long mod = (long) (1e9 + 7);

            int N = sc.nextInt();
            long[] A = new long[N];
            for (int i = 0; i < N; i++) {
                A[i] = sc.nextInt();
            }

            long[] cumsum = new long[N + 1];
            for (int i = 0; i < N; i++) {
                cumsum[N - 1 - i] += cumsum[N - i] + A[N - 1 - i];
                cumsum[N - 1 - i] %= mod;
            }

            long sum = 0;
            for (int i = 0; i < N; i++) {
                sum += A[i] * cumsum[i + 1];
                sum %= mod;
            }

            System.out.println(sum);
        }
    }
}


import java.util.Scanner;

//
class Main{
    final static int MOD = (int)Math.pow(10, 9) + 7;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] a = new int[N];

        long sum = 0;	// n-1項までの合計
        long ans = 0;
        for(int i = 0; i < N; i++) {
            a[i] = sc.nextInt();
            sum += a[i];
            sum %= MOD;
        }

        for(int i = 0; i < N - 1; i++) {
        	sum -= a[i];
        	if(sum < 0) sum += MOD;
            ans += a[i] * sum;
            ans %= MOD;
        }

        System.out.println(ans % MOD);
    }

}


import java.util.Scanner;
public class Main {

		public static void main(String[] args) {
			try(Scanner sc = new Scanner(System.in)){
				int n = sc.nextInt();
				long[] s = new long[n];
				long[] f = new long[n+1];
				int mod = 1000000007;
				f[0] = 0;
				 long d = 0;
				for(int x = 0;x < n;x++) {
					s[x] = sc.nextInt();
				}
				for(int x = 1;x <= n;x++) {
					f[x] = f[x-1]+s[x-1];
				}
				for(int x = 0;x < n;x++) {
					long sum = f[n] - f[x + 1];
					d += s[x] * sum;
					d = d % mod;
				}
				System.out.println(d);
			}
		}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int mod = 1000000007;
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        int[] a = new int[n];
        long[] b = new long[n + 1];
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(sc.next());
            b[i + 1] = b[i] + a[i];
        }
        long result = 0;
        for (int i = 0; i < n; i++) {
            long sum = (b[n] - b[i + 1]) % mod;

            result = (result + ((long) a[i] * sum) % mod) % mod;
        }
        System.out.println(result);
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        Scanner sc = new Scanner(System.in);
        int N = Integer.parseInt(sc.next());
        int[] A = new int[N];
        for (int i = 0; i < N; i++) {
            A[i] = Integer.parseInt(sc.next());
        }
        long sum = 0;
        long mod = 1000000007;
        long[][] cache = new long[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                if (cache[i][j] == 0) {
                    cache[i][j] = ((A[i] % mod) * (A[j] % mod)) % mod;
                }
                sum = (sum + cache[i][j]) % mod;
            }
        }
        System.out.println(sum);
    }
}


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

public class Main {
	static final int INF = (int) (1e9 + 10);
	static final long MOD = (int) (1e9 + 7);
	static final int N = (int) (4e5 + 5);

	// static ArrayList<Integer>[] graph;
	// static boolean visited[];
	// static long size[];
	static long findProductSum(long A[], int n) {

		long array_sum = 0;
		for (int i = 0; i < n; i++)
			array_sum = (array_sum + A[i]) ;

		long array_sum_square = (array_sum * array_sum) % MOD;

		long individual_square_sum = 0;
		for (int i = 0; i < n; i++)
			individual_square_sum = (individual_square_sum + A[i] * A[i]) % MOD;
		if(array_sum_square<individual_square_sum)
			array_sum_square+=MOD;
		return (((array_sum_square - individual_square_sum)/2)%MOD);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		FastReader sc = new FastReader();
		PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		// Scanner scn = new Scanner(System.in);
		//
		int n = sc.nextInt();
		long[] arr = sc.nextLongArray(n);
		pr.println(findProductSum(arr, n));
		//
		// Coded to Perfection by Rohan Mukhija
		pr.flush();
		pr.close();
	}

	/*
	 * Template From Here
	 */
	static class Pair implements Comparable<Pair> {
		int u;
		int v;

		Pair(int u, int v) {
			this.u = u;
			this.v = v;

		}

		public int compareTo(Pair compareEdge) {
			return Long.compare(this.v, compareEdge.v);
		}
	};

	private static boolean possible(long[] arr, double mid, long k) {
		long c = 0;
		for (int i = 0; i < arr.length; i++) {
			c += ((arr[i]) / mid);
			if (c % arr[i] == 0)
				c--;
		}
		// System.out.println(mid+" "+c+" "+k);
		if (c <= k)
			return true;
		return false;
	}

	static void sort(long[] a) {
		ArrayList<Long> l = new ArrayList<>();
		for (long i : a)
			l.add(i);
		Collections.sort(l);
		for (int i = 0; i < a.length; i++)
			a[i] = l.get(i);
	}

	static void sort(int[] a) {
		ArrayList<Integer> l = new ArrayList<>();
		for (int i : a)
			l.add(i);
		Collections.sort(l);
		for (int i = 0; i < a.length; i++)
			a[i] = l.get(i);
	}

	public static int lowerBound(ArrayList<Integer> array, int length, long value) {
		int low = 0;
		int high = length;
		while (low < high) {
			final int mid = (low + high) / 2;
			if (value <= array.get(mid)) {
				high = mid;
			} else {
				low = mid + 1;
			}
		}
		return low;
	}

	public static long mul(long a, long b) {
		return (a * b) % MOD;
	}

	static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}

		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextLongArray(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}
	}

	static long gcd(long a, long b) {
		if (a == 0)
			return b;
		return gcd(b % a, a);
	}

	static long lcm(long a, long b) {
		return (a * b) / gcd(a, b);
	}

	public static void sortbyColumn(int[][] att, int col) {
		// Using built-in sort function Arrays.sort
		Arrays.sort(att, new Comparator<int[]>() {

			@Override
			// Compare values according to columns
			public int compare(final int[] entry1, final int[] entry2) {

				// To sort in descending order revert
				// the '>' Operator
				// if (entry1[col] > entry2[col])
				// return 1;
				// else //(entry1[col] >= entry2[col])
				// return -1;
				return new Integer(entry1[col]).compareTo(entry2[col]);
				// return entry1[col].
			}
		}); // End of function call sort().
	}

	public static void sortbyColumn(double[][] att, int col) {
		// Using built-in sort function Arrays.sort
		Arrays.sort(att, new Comparator<double[]>() {

			@Override
			// Compare values according to columns
			public int compare(final double[] entry1, final double[] entry2) {

				// To sort in descending order revert
				// the '>' Operator
				// if (entry1[col] > entry2[col])
				// return 1;
				// else //(entry1[col] >= entry2[col])
				// return -1;
				return new Double(entry1[col]).compareTo(entry2[col]);
				// return entry1[col].
			}
		}); // End of function call sort().
	}

	static class pair {
		int V, I;

		pair(int v, int i) {
			V = v;
			I = i;
		}
	}

	public static int[] swap(int data[], int left, int right) {
		int temp = data[left];
		data[left] = data[right];
		data[right] = temp;
		return data;
	}

	public static int[] reverse(int data[], int left, int right) {
		while (left < right) {
			int temp = data[left];
			data[left++] = data[right];
			data[right--] = temp;
		}
		return data;
	}

	public static boolean findNextPermutation(int data[]) {
		if (data.length <= 1)
			return false;

		int last = data.length - 2;
		while (last >= 0) {
			if (data[last] < data[last + 1]) {
				break;
			}
			last--;
		}
		if (last < 0)
			return false;

		int nextGreater = data.length - 1;
		for (int i = data.length - 1; i > last; i--) {
			if (data[i] > data[last]) {
				nextGreater = i;
				break;
			}
		}
		data = swap(data, nextGreater, last);
		data = reverse(data, last + 1, data.length - 1);
		return true;
	}

	static long ncr(long a, long b) {
		if (b > a - b)
			return ncr(a, a - b);
		long ansMul = 1;
		long ansDiv = 1;
		for (int i = 0; i < b; i++) {
			ansMul *= (a - i);
			ansDiv *= (i + 1);
			ansMul %= MOD;
			ansDiv %= MOD;
		}

		long ans = ansMul * power(ansDiv, MOD - 2, MOD) % MOD;

		return ans;
	}

	static long __gcd(long n1, long n2) {
		long gcd = 1;

		for (int i = 1; i <= n1 && i <= n2; ++i) {
			// Checks if i is factor of both integers
			if (n1 % i == 0 && n2 % i == 0) {
				gcd = i;
			}
		}
		return gcd;
	}

	static long power(long prev, long n2, long mod2) {
		long res = 1;

		prev = prev % mod2;

		if (prev == 0)
			return 0;
		while (n2 > 0) {

			if ((n2 & 1) == 1)
				res = (res * prev) % mod2;

			n2 = n2 >> 1;
			prev = (prev * prev) % mod2;
		}
		return res;
	}

	static long modInverse(long fac2, int p) {
		return power(fac2, p - 2, p);
	}

	static boolean isPrime(int n) {
		// Corner cases
		if (n <= 1)
			return false;
		if (n <= 3)
			return true;

		// This is checked so that we can skip
		// middle five numbers in below loop
		if (n % 2 == 0 || n % 3 == 0)
			return false;

		for (int i = 5; i * i <= n; i = i + 6)
			if (n % i == 0 || n % (i + 2) == 0)
				return false;

		return true;
	}

	public static BigInteger lcmm(String a, String b) {
		BigInteger s = new BigInteger(a);
		BigInteger s1 = new BigInteger(b);
		BigInteger mul = s.multiply(s1);
		BigInteger gcd = s.gcd(s1);
		BigInteger lcm = mul.divide(gcd);
		return lcm;
	}
	/*
	 * static boolean prime[] = new boolean[10000007]; static int spf[] = new
	 * int[10000007];
	 *
	 * public static void sieveOfEratosthenes(int n) { for (int i = 2; i < n;
	 * i++) prime[i] = true; for (int p = 2; p * p <= n; p++) {
	 *
	 * if (prime[p] == true) {
	 *
	 * for (int i = p * p; i <= n; i += p) { prime[i] = false; spf[i] = p; } } }
	 * }
	 */
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author test
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        abc177_c solver = new abc177_c();
        solver.solve(1, in, out);
        out.close();
    }

    static class abc177_c {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int N = in.nextInt();
            long[] A = new long[N];
            for (int i = 0; i < N; i++) {
                A[i] = in.nextLong();
            }
            Arrays.sort(A);
            long sum = 0;
            long mod = 1000000007;
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    if (A[i] < A[j]) {
                        sum = (sum + ((A[i] * A[j]) % mod)) % mod;
                    }
                }
            }
            out.println(sum);
        }

    }
}


import java.io.*;
import java.util.*;
class Main
{
	public static void main(String args[]) throws IOException
	{
		try{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int n=0;
		n=Integer.parseInt(br.readLine());
		String brr[]=br.readLine().split(" ");
		long ar[]=new long[n];
		for(int i=0;i<n;i++)
		{
			ar[i]=Long.parseLong(brr[i]);
		}
        long sum[] = new long[n];
        sum[n - 1] = ar[n - 1];
        for (int i = n - 2; i >= 0; i--)
            sum[i] = sum[i + 1] + ar[i];
        long res = 0;
        for (int i = 0; i < n - 1; i++)
            res += (sum[i + 1] * ar[i]);
        System.out.println((long)(res%(1e9+7)));
    }
	catch(Exception e){}
}}


import java.io.*;
import java.util.*;
public class Main {
    final static long mod = 1000000007;

    public static void main(String[] args) {
        InputReader sc = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        Random gen = new Random();
        int test = 1;//sc.nextInt();
        while(test-->0) {
           long ans = 0;
           int n = sc.nextInt();
           long [] ar = new long[n];
           long sum = 0;
            long [] pre = new long[n];
           for(int i=0;i<n;i++) {
               ar[i] = sc.nextLong();
                sum+=ar[i];
                pre[i] = sum;
           }

          for(int i=0;i<n;i++)
          {
             // ans = (ans%mod + ((ar[i]%mod)*((sum-pre[i])%mod))%mod)%mod;
              ans = (ans%mod + (((ar[i]%mod)*((sum-pre[i])%mod))%mod) )%mod;
          }

            pw.println(ans);

        }
        pw.flush();
        pw.close();

    }

    static class Data implements Comparable<Data>{
        int x;
        int y;

        public Data (int m, int n) {
            x = m;
            y = n;
        }
        @Override
        public int compareTo(Data o) {
            return y - o.y;
        }
    }

    static class InputReader {

        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;

        public InputReader(InputStream st) {
            this.stream = st;
        }

        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int [] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public static int[] shuffle(int[] a, Random gen)
        { for(int i = 0, n = a.length;i < n;i++)
        { int ind = gen.nextInt(n-i)+i;
            int d = a[i];
            a[i] = a[ind];
            a[ind] = d;

        }
            return a;
        }
        public static char[] shuffle(char[] a, Random gen)
        { for(int i = 0, n = a.length;i < n;i++)
        { int ind = gen.nextInt(n-i)+i;
            char d = a[i];
            a[i] = a[ind];
            a[ind] = d;

        }
            return a;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Pranay2516
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        C solver = new C();
        solver.solve(1, in, out);
        out.close();
    }

    static class C {
        public void solve(int testNumber, FastReader in, PrintWriter out) {
            int n = in.nextInt(), a[] = in.readIntArray(n), mod = (int) 1e9 + 7;
            long[] pref = new long[n];
            pref[n - 1] = a[n - 1];
            for (int i = n - 2; i >= 0; --i) pref[i] = ((pref[i + 1] + a[i]) + mod) % mod;
            long sum = 0;
            for (int i = 0; i < n - 1; ++i) sum = ((sum % mod) + ((pref[i + 1] * a[i] + mod) % mod) + mod) % mod;
            out.println(sum);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[(int) size];
            for (int i = 0; i < size; i++) array[i] = nextInt();
            return array;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


import java.util.*;
import java.io.*;
class Main{
    static class InputReader {

        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }

    }
    static class OutputWriter {
		private final PrintWriter writer;

		public OutputWriter(OutputStream outputStream) {
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
		}

		public OutputWriter(Writer writer) {
			this.writer = new PrintWriter(writer);
		}

		public void print(Object...objects) {
			for (int i = 0; i < objects.length; i++) {
				if (i != 0)
					writer.print(' ');
				writer.print(objects[i]);
			}
		}

		public void printLine(Object...objects) {
			print(objects);
			writer.println();
		}

		public void close() {
			writer.close();
		}

		public void flush() {
			writer.flush();
		}

		}
    static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
    static int mod = (int)(1e9+7);
    public static long pow(long a,long b)
    {
        long ans = 1;
        while(b> 0)
        {
            if((b & 1)==1){
                ans = (ans*a) % mod;
            }
            a = (a*a) % mod;
            b = b>>1;
        }
        return ans;
    }

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        int n = in.nextInt();
        long[] arr = new long[n];
        for(int i=0;i<n;i++)
        {
            arr[i] = in.nextLong();
        }
        long sumTillnow = 0;
        long res = 0;
        for(int i=n-1;i>=0;i--)
        {
            res = (res+(arr[i]*sumTillnow))%mod;
            sumTillnow+=arr[i];
            assert sumTillnow>=0;
        }
        out.printLine(res);
        out.flush();
        out.close();
    }
}


import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws FileNotFoundException {

		//    	File file = new File("src/in.txt");
		//    	Scanner sc = new Scanner(file);

		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		BigInteger sum = BigInteger.valueOf(0);
		BigInteger sqsum = BigInteger.valueOf(0);

		for(int i=0;i<N;i++) {
			int A = sc.nextInt();
			BigInteger bigA = BigInteger.valueOf(A);
			sum = sum.add(bigA);
			sqsum = sqsum.add(bigA.pow(2));
		}
		BigInteger sumsq = sum.pow(2);
		BigInteger d = (sumsq.subtract(sqsum)).divide(BigInteger.valueOf(2));

		BigInteger ans = d.mod(BigInteger.valueOf(1000000007));

		System.out.println(ans);
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long INF = (long)Math.pow(10, 9) + 7;
        int n = sc.nextInt();
        long[] a = new long[n];
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextLong();
        }
        long sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        long res = 0;
        for (int i = 0; i < a.length - 1; i++) {
            sum -= a[i];
            res += a[i] * (sum % INF);
            res %= INF;
        }
        System.out.println(res);
        sc.close();
    }
}


import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
	static long mod = (long)(1e9+7);
	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	public static void main(String[] args)throws IOException {
		Scanner sc =new Scanner(System.in);
		int n =  sc.nextInt();
		long arr[] = new long[n+1];
		long total= 0;
		for(int i=1;i<=n;i++){
			arr[i] = sc.nextLong();
		}

		total=0;
		long ans = 0;
		for(int i=1;i<=n;i++){
			long p = (arr[i]%mod*total%mod)%mod;
			ans = (ans%mod + p%mod)%mod;
			total=(total%mod+arr[i]%mod)%mod;
		}
		System.out.println(ans);
	}

	public static long power(long a, long b){
		long temp = 0l;
		if(b==0)
			return 1l;

		temp = power(a, b/2);
		if(b%2==0)
			return (temp%mod*temp%mod)%mod;
		else return (temp%mod*(temp%mod*a%mod)%mod)%mod;
	}

	public static LinkedList<Integer> comp(LinkedList<Integer> q){
		LinkedList<Integer> op = new LinkedList<>();
		Stack<Integer> stack = new Stack<>();
		while(q.size()>0){
			stack.push(q.pop());
		}
		while(stack.size()>0){
			op.addLast(stack.pop());
		}
		return op;
	}

	public static ArrayList<Integer> primefactor(int n){
		int sqrt = (int)Math.sqrt(n);
		ArrayList<Integer> al = new ArrayList<>();
		while(n%2==0){
			al.add(2);
			n/=2;
		}
		for(int i=3;i<=sqrt;i+=2){
			while(n%i==0){
				al.add(i);
				n/=i;
			}
		}
		if(n>2)
			al.add(n);
		return al;
	}

	public static long sum(long val){
		long fg =0 ;
		while(val!=0){
			fg+=val%10;
			val/=10;
		}
		return fg;
	}

	public static ArrayList<Long> factor(long n){
		long sqrt = (long)Math.sqrt(n);
		ArrayList<Long> al = new ArrayList<>();
		for(long i=1;i<=sqrt;i++){
			if(n%i!=0)
				continue;
			long first = i;
			long second = n/i;
			al.add(i);
			if(first==second){
				continue;
			}
			al.add(n/i);
		}
		return al;
	}

	public static ArrayList<Integer> comp(){
		ArrayList<Integer> al = new ArrayList<>();
			int n = (int)2e5;
			boolean arr[] = new boolean[n+1];
			int sqrt = (int)Math.sqrt(n);
			for(int i=2;i<=sqrt;i++){
				if(arr[i]==false){
					for(int j=i*i;j<=n;j+=i){
						arr[j]=true;
					}
				}
			}
			for(int i=2;i<=n;i++){
				if(arr[i]==false)
					al.add(i);
			}

		return al;
	}

	public static class pair{
		int x;
		int y;
		pair(int x, int y){
			this.x=x;
			this.y=y;
		}
	}

	public static class comp implements Comparator<pair>{
		public int compare(pair o1, pair o2){
			return o2.y-o1.y;
		}
	}

	static class Node{
		int node;
		int d;
		ArrayList<Integer> al = new ArrayList<>();
	}

	static int gcd(int a, int b)
    {
      if (b == 0)
        return a;
      return gcd(b, a % b);
    }

	static class FastReader
	{
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public FastReader()
		{
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public FastReader(String file_name) throws IOException
		{
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException
		{
			byte[] buf = new byte[64]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1)
			{
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException
		{
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
			{
				ret = ret * 10 + c - '0';
			}  while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException
		{
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			}
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException
		{
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			}
			while ((c = read()) >= '0' && c <= '9');

			if (c == '.')
			{
				while ((c = read()) >= '0' && c <= '9')
				{
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException
		{
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException
		{
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException
		{
			if (din == null)
				return;
			din.close();
		}
	}
}


import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    var m = 1000000000 + 7;

    var sc = new Scanner(System.in);

    var n = sc.nextInt();
    var a = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt() % m;
    }

    long answer = 0;
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        answer = (answer + (long)a[i] * a[j] % m) % m;
      }
    }

    System.out.println(answer);

  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        String[] input_array = br.readLine().split(" ");

        long result = 0;
        long mod = 1000000000 + 7;

        for(int i = 0; i < N; i++) {
            long num_i = Long.parseLong(input_array[i]);

            for(int j = i + 1; j < N; j++) {
                long num_j = Long.parseLong(input_array[j]);
                result += num_i * num_j;
                result = result % mod;
            }
        }

        pw.println(result);
        br.close();
        pw.close();
    }
}


import java.util.*;
import java.io.*;
import java.math.*;
	        public class Main {
	        	static int mxn = (int)1e9 + 7;
//	        	static int check(String s, String t) {
//	        	}
	        public static void main(String args[]) throws IOException {
	        	FastReader sc = new FastReader();
	        	int n = sc.nextInt();
	        	long[] arr = sc.readLongArray(n);
	        	long sum = 0;
	        	for(int i = 0;i<n-1;i++)  {
	        		for(int j = i+1;j<n;j++) {
	        			sum += (arr[i]*arr[j])%mxn;
	        		}
	        	}

	        	pn(sum%mxn);
	       }
	       static void p(Object p){System.out.print(p);}
	       static void pn(){System.out.println();}
	       static void pn(Object o){System.out.println(o);}

	       static class FastReader {
	       static BufferedReader br;
	       StringTokenizer st;
	       public FastReader() {
	       br = new BufferedReader(new InputStreamReader(System.in));
	       }

	       String next(){
	       while (st == null || !st.hasMoreElements()) {
	            try{
	                st = new StringTokenizer(br.readLine());
	            }
	            catch (IOException  e) {
	                e.printStackTrace();
	            }}
	            return st.nextToken();
	            }

	            int nextInt(){
	                return Integer.parseInt(next());
	            }

	            long nextLong(){
	                return Long.parseLong(next());
	            }

	            static int max(int[] a){
	            int max = Integer.MIN_VALUE;
	            for(int i : a) max = Math.max(max, i);
	            return max;
	            }

	            public int[] readIntArray(int n) {
	            int[] arr = new int[n];
	            for(int i=0; i<n; ++i) arr[i]=nextInt();
	            return arr;
	            }

	            public long[] readLongArray(int n){
	            long[] arr = new long[n];
	            for(int i=0; i<n; ++i) arr[i]=nextLong();
	            return arr;
	            }

	            public int[][] readIntArray(int m, int n){
	            int[][] arr = new int[m][n];
	            for(int i = 0;i<m;i++)
	            for(int j = 0;j<n;j++) arr[i][j] = nextInt();
	            return arr;
	            }

	            public String[] readStringArray(int n) {
	            String[] arr = new String[n];
	            for(int i=0; i<n; ++i) arr[i]= nextLine();
	            return arr;
	            }

	            double nextDouble() {return Double.parseDouble(next());}

	            String nextLine() {
	            String str = "";
	            try{str = br.readLine();}
	            catch (IOException e) {e.printStackTrace();}
	            return str;}}
	        }


import java.io.*;

class Main
{
    public static void main(String args[])throws Exception
    {
        BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder();
        int n=Integer.parseInt(bu.readLine());
        String s[]=bu.readLine().split(" ");
        int i,a[]=new int[n];
        long sum=0,res=0,M=1000000007;
        for(i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(s[i]);
            sum+=a[i];
        }

        for(i=0;i<n;i++)
        {
            sum-=a[i];
            res+=sum%M*a[i]%M;
            res%=M;
        }
        System.out.print(res);
    }
}