【前缀和】一维前缀和 & 二维前缀和

目录

一、一维前缀和

1.前缀和(模板)

2.最大子段和

二、二维前缀和

1.二维前缀和(模板)

2.激光炸弹


一、一维前缀和

1.前缀和(模板)

【模板】前缀和

答案如下:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;

const int N = 1e5 + 10;
long long a[N];

int main()
{
    int n,m;
    a[0] = 0;
    cin >> n >>m;
    for(int i = 1; i <= n; i++)
    {
        int e; cin >> e;
        a[i] = e + a[i-1];
    }
    while(m--)
    {
        int l,r;
        cin >> l >> r;
        long long sum = a[r] - a[l-1];
        cout << sum << endl;
    }
    return 0;
}

2.最大子段和

P1115 最大子段和 - 洛谷

答案如下:

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

const int N = 2e5 + 10;
int a[N];

int main()
{
	int n; cin >> n;
	for(int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	int cnt = 0;
	int max = -1e5;
	for(int i = 1; i <= n; i++)
	{
		cnt += a[i];
		max = max < cnt ? cnt : max; 
		if(cnt < 0) cnt = 0;
	}
	cout << max;
	return 0;
}

二、二维前缀和

1.二维前缀和(模板)

【模板】二维前缀和

答案如下:

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

const int N = 1e3 + 10;
long long arr[N][N];

int main()
{
    int n,m,q;
    cin >> n >> m >> q;
    for(int i = 1; i <= n; ++i)
    {
        for(int j = 1; j <= m; ++j)
        {
            int e; cin >> e;
            arr[i][j] = arr[i][j-1] + arr[i-1][j] - arr[i-1][j-1] + e;
        }
    }
    while(q--)
    {
        int x1,y1,x2,y2;
        cin >> x1 >> y1 >> x2 >> y2;
        long long sum = arr[x2][y2] - arr[x2][y1-1] - arr[x1-1][y2] + arr[x1-1][y1-1];
        cout << sum << endl;
    }
    return 0;
}

2.激光炸弹

P2280 HNOI2003 激光炸弹 - 洛谷

答案如下:

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

const int N = 5010;
int a[N][N];
int f[N][N]; 

int main()
{
	int n,m;
	cin >> n >> m;
	while(n--)
	{
		int x,y,v;
		cin >> x >> y >> v;
		x++; y++;
		a[x][y] += v;
	}
	n = 5001;
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			f[i][j] = f[i][j-1] + f[i-1][j] - f[i-1][j-1] + a[i][j];
		}
	}
	
	int ret = 0;
    m = min(m,n);
	for(int i = m; i <= n; i++)
	{
		int x1 = i - m + 1;
		for(int j = m; j <= n; j++)
		{
			int y1 = j - m + 1;
			ret = max(ret,f[i][j] - f[i][y1-1] - f[x1-1][j] + f[x1-1][y1-1]); 
		}
	}
	cout << ret << endl;
	return 0;
}
相关推荐
SZYSK1 分钟前
OpenHarmony 上读卡、推理和双屏刷新抢 CPU:核验机与消费机的调度差
物联网·算法·harmonyos·1024程序员节
ShineWinsu14 分钟前
对于Qt:QPushButton常见属性的解析
开发语言·c++·qt·api·gui·按钮·qpushbutton
Ivanqhz20 分钟前
MoE + LLM 应用
数据库·人工智能·pytorch·python·深度学习·算法·1024程序员节
Lhan.zzZ24 分钟前
用 Qt 构建线程安全的通讯静态库:从线程亲和性到完整工程
c++·vscode·qt·tcp/ip·udp
lpfasd12335 分钟前
推荐算法进化史
算法·机器学习·推荐算法
xiaoye-duck42 分钟前
《C++ 项目:手写大模型接入 SDK》DeepSeek接口设计(上):初始化和全量响应
开发语言·网络·c++·语言模型
Pniubi1 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
fpcc1 小时前
跟我学c++中级篇—streambuf在glog中的应用分析
开发语言·c++
码匠许师傅1 小时前
【C++三方组件】OpenCV:计算机视觉的事实标准
c++
黎相思1 小时前
BTree
数据结构·b树·b+树