【基础算法】前缀和

前缀和

为什么要学前缀和?

例题:一维前缀和

暴力解法

#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int a[N];
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++) cin >> a[i];
	while (m--)
	{
		int l, r;
		cin >> l >> r;
		int res = 0;
		for (int i = l; i <= r; i++)
		{
			res += a[i];
		}
		cout << res << endl;
	}
	return 0;
}

一维前缀和推导:

Si=a1+a2+...+ai

SrSl1=al+al+1+...+ar

标准前缀和解法

#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int a[N], s[N];
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		s[i] = s[i - 1] + a[i];// 初始化了前缀和数组
	}
	while (m--)
	{
		int l, r;
		cin >> l >> r;
		cout << s[r] - s[l - 1] << endl;
	}
	return 0;
}

例题:二维前缀和

暴力解法

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N];
int main()
{
	cin >> n >> m >> q;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> a[i][j];
	while (q--)
	{
		int x1, y1, x2, y2;
		cin >> x1 >> y1 >> x2 >> y2;
		int res = 0;
		for (int i = x1; i <= x2; i++)
			for (int j = y1; j <= y2; j++)
				res += a[i][j];
		cout << res << endl;
	}
	return 0;
}

二维前缀和推导:

Si,j=Si1,j+Si,j1Si1,j1+ai,j

res=Sx2,y2Sx11,y2Sx2,y11+Sx11,y11

标准二维前缀和解法

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N], s[N][N];
int main()
{
	cin >> n >> m >> q;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
		{
			cin >> a[i][j];
			s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j]; // 二维前缀和的初始化
		}
	while (q--)
	{
		int x1, y1, x2, y2;
		cin >> x1 >> y1 >> x2 >> y2;
		cout << s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1] << endl;
	}
	return 0;
}
posted @   高明y  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示