二维前缀和
11P1719 最大加权矩形 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <bits/stdc++.h>
using namespace std;
int a[200][200];
int qz[200][200];
int sum[200][200];
int main() {
int ma = -1e8;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
qz[i][j] = qz[i][j - 1] + a[i][j]; //某一行上前缀和(一维
sum[i][j] = sum[i - 1][j] + qz[i][j]; //二维(上一行的前缀和加上这一行的前缀和)
}
}
for (int x1 = 1; x1 <= n; x1++) {
for (int y1 = 1; y1 <= n; y1++) {
for (int x2 = 1; x2 <= n; x2++) {
for (int y2 = 1; y2 <= n; y2++) {
if (x1 > x2 || y1 > y2)
continue;
ma = max(ma, sum[x2][y2] - sum[x1 - 1][y2] - sum[x2][y1 - 1] + sum[x1 - 1][y1 - 1]);//某一小片矩形方阵的和
}
}
}
}
cout << ma;
return 0;
}
一维前缀和
P1115 最大子段和 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 100;
int a[N], b[N], c[N];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
c[i] = c[i - 1] + a[i];//前缀和
}
b[1] = a[1];
int mi =min(0,c[1]);//初始化最小值mi
for (int i = 2; i <= n; i++) {
b[i] = c[i] - mi;//现前缀和减去原最小前缀和(即当前最大字段和)存在b数组里
mi = min(mi, c[i]);//不断更新最小前缀和
}
sort(b + 1, b + 1 + n);//排序找最大的最大字段和
cout << b[n];
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 100;
int a[N], b[N], c[N];
int main() {
int n, max, a;
cin >> n >> max;
int mi = max;
for (int i = 1; i < n; i++) {
cin >> a;
if (mi < 0)
mi = 0;//注意!!!这里的判断要放在加数的前面(如果所给的数全是负数,顺序颠倒的话就判断不出了)
mi += a;
if (mi > max)
max = mi;
}
cout << max;
return 0;
}