LanQiaoTestCodes/求和.java

36 lines
698 B
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package LanQiaoOJ;
import java.util.Scanner;
/*
* 问题描述
给定n个整数a1,a2,··,am,求它们两两相乘再
相加的和,即:
S=a1·a2+a1·a3+·+a1·am+a2·a3+
输入格式
输入的第一行包含一个整数几。
第二行包含n个整数a1,a2,··,an*/
//方法合并化解S1=a1(a2+a3+...+an-1)
public class 求和 {
static int N=200010;
static long[]a=new long[N];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++) {
a[i]=sc.nextInt();
}
//最终结果
long ans=0;
//记录i-1个数的和
long sum=0;
for(int i=1;i<=n;i++) {
ans+=a[i]*sum;
sum+=a[i];
}
//时间复杂度为O(n)
System.out.print(ans);
}
}