求和(前缀和)

思路:

要是直接算的话那么会使得时间复杂度很高的,所以我们可以用空间换时间:
还有需要注意int类型的大小满不满足,

#include<iostream>
using namespace std;
int n;
int g[200000];
 
int main()
{
     
    cin >> n;
    long long total = 0;
    for(int i = 0; i < n; i++) {
        cin >> g[i];
        total += g[i];
    }
    if(n == 1) {
        cout << g[0];
    }
    long long ans = 0;
    for(int i = 0; i < n ;i++) {
        ans += g[i]*(total - g[i]);
        total = total - g[i];
    }
     
    cout <<ans;
    return 0;
}
posted @ 2023-09-02 18:52  铜锣湾陈昊男  阅读(5)  评论(0)    收藏  举报