P8772 [蓝桥杯 2022 省 A] 求和

题目描述:

解题思路:

首先这题我们可以直接用两个for循环嵌套来控制两个变量来求值,但是这样做时间复杂度高。这里我们用到了一个前缀和差的方法。通过for循环变量第一个变量,用和差的方法的到第二个量,这样就只用了一次循环,大大减少了时间复杂度。需要注意的是,这题有时间限制开辟大数组时需要开在全局中(程序留给全局的空间大,而留给main函数内的空间少)。

样例代码:

cpp 复制代码
#include <iostream>
#include <stdio.h>
using namespace std;

int n;
int arr[10000] = { 0 };
int sum[10000] = { 0 };
int ans = 0;

int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> arr[i];
		sum[i] = sum[i - 1] + arr[i];
	}
	for (int i = 1; i <= n; i++)
	{
		ans = ans + arr[i] * (sum[n] - sum[i]);
	}
	printf("%d", ans);
	return 0;
}
相关推荐
We་ct14 分钟前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
mit6.82423 分钟前
tabbi风波|开源协议
算法
是梦终空11624 分钟前
C++中的职责链模式变体
开发语言·c++·算法
仰泳的熊猫28 分钟前
题目2270:蓝桥杯2016年第七届真题-四平方和
c++·算法·蓝桥杯
CoovallyAIHub28 分钟前
CVPR 2026 | VisualAD:去掉文本编码器,纯视觉也能做零样本异常检测
算法·架构·github
CoovallyAIHub29 分钟前
东南大学提出 AutoIAD:多 Agent 驱动的工业异常检测自动化框架
算法·架构·github
ccLianLian40 分钟前
算法·字符串
算法·哈希算法
sinat_286945191 小时前
spec vs plan ai coding
人工智能·深度学习·算法·chatgpt·prompt