前缀和与差分

99. 激光炸弹

在这里插入图片描述
在这里插入图片描述

这道题用到了二维前缀和

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 5005;

int g[N][N];

int main(void)
{
	int n, r;
	int x, y, w;
	cin >> n >> r;
	int a = r, b = r;
	for (int i = 0; i < n; i++){
		cin >> x >> y >> w;
		x++, y++;
		a = max(a, x), b = max(b, y);
		g[x][y] = w;
	}
	for (int i = 1; i <= a; i++)
		for (int j = 1; j <= b; j++){
			g[i][j] += g[i - 1][j] + g[i][j - 1] - g[i - 1][j - 1];//注意这里是+= 
		}
	int res = 0;
	for (int i = r; i <= a; i++)
		for (int j = r; j <= b; j++){
			res = max(res, g[i][j] - g[i - r][j] - g[i][j - r] + g[i - r][j - r]);
		}
	cout << res << endl;
	return 0;
}

100. IncDec序列

在这里插入图片描述
在这里插入图片描述
题解:https://www.acwing.com/solution/acwing/content/816/

#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 5;
typedef long long ll;

int arr[N], c[N];

int main(void)
{
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++){
		scanf("%d", &arr[i]);
		c[i] = arr[i] - arr[i - 1];
	}
	ll pos = 0, neg = 0;
	for (int i = 2; i <= n; i++)
		if (c[i] > 0) pos += c[i];
		else neg -= c[i];
	cout << min(pos, neg) + abs(pos - neg) << endl;
	cout << abs(pos - neg) + 1 << endl; 
	return 0;
}

101. 最高的牛

在这里插入图片描述
在这里插入图片描述

这道题用到了差分,差分的意义在于题目中要进行多次对区间[a, b]中数值的减1,复杂度为O(n),使用差分的话仅改变差分数组中区间的首尾元素,复杂度为O(1)
因为这道题中给出的关系对可能存在重复,所以要用一个map或者数组来进行判断是当前的关系对否出现过

关于差分的一些格式:https://blog.csdn.net/Healer66/article/details/87201014

#include <cstdio>
#include <map>
#include <iostream>
using namespace std;
const int N = 1e4 + 5;

int c[N];
map<pair<int, int>, bool>pair_map;

int main(void)
{
	int n, p, h, m;
	int a, b;
	cin >> n >> p >> h >> m;
	for (int i = 0; i < m; i++){
		cin >> a >> b;
		if (a > b) swap(a, b);
		if (!pair_map[make_pair(a, b)]){
			pair_map[make_pair(a, b)] = true;
			c[a + 1]--; c[b]++;
		}
	}
	c[1] = h;
	for (int i = 1; i <= n; i++){
		c[i] += c[i - 1];
		cout << c[i] << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值