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

目录

一、一维前缀和

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;
}
相关推荐
luj_17681 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
zmzb01032 小时前
C++课后习题训练记录Day175
开发语言·c++
啦啦啦啦啦zzzz2 小时前
工具:动态类工厂和用配置文件存储属性
c++·设计模式·工具·动态工厂
脱胎换骨-军哥2 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
木木子223 小时前
# 鸿蒙 ArkTS 实战:秒表 Stopwatch(示例 5)
数据结构·华为·list·harmonyos
geats人山人海4 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
漂流瓶jz4 小时前
UVA-12627 奇怪的气球膨胀 题解答案代码 算法竞赛入门经典第二版
算法·图论·递归·aoapc·算法竞赛入门经典·uva·12627
迷途之人不知返4 小时前
lambda表达式
c++
jarvisuni4 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
@三十一Y4 小时前
C++:红黑树的实现
开发语言·c++