差分
// 每日一题
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 200010;
int n;
int a[N], s[N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
s[i] = s[i - 1] + a[i]; // 前缀和
}
LL res = 0;
for (int i = 1; i <= n - 1; i++)
{
res = res + (LL)a[i] * (s[n] - s[i]);
}
cout << res << endl;
return 0;
}
什么是差分?
差分就是一个序列中后一项减前一项的过程。
差分数组就是一个序列中后一项减前一项的值组成的一个新的序列。
例如
有一个序列为:\([2,1,4,6,3,2]\) 那么这个序列的差分数组为:\([2,-1,3,2,-3,-1]\)
差分可以解决什么问题?
- 区间修改(将 \(O(n)\) 时间的修改区间变为 \(O(1)\) 时间的修改端点)
例题:一维差分
暴力:
#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, c;
cin >> l >> r >> c;
for (int i = l; i <= r; i ++)
a[i] += c;
}
for (int i = 1; i <= n; i++) cout << a[i] << ' ';
return 0;
}
差分:
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int a[N], b[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
b[i] = a[i] - a[i - 1]; // 初始化差分数组
}
while (m --)
{
int l, r, c;
cin >> l >> r >> c;
b[l] += c;
b[r + 1] -= c;
}
for (int i = 1; i <= n; i++) b[i] += b[i - 1]; // 前缀和
for (int i = 1; i <= n; i++) cout << b[i] << ' ';
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, c;
cin >> x1 >> y1 >> x2 >> y2 >> c;
for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
a[i][j] += c;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
cout << a[i][j] << ' ';
cout << endl;
}
return 0;
}
差分:
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, q;
int a[N][N], b[N][N];
void modify(int x1, int y1, int x2, int y2, int c)
{
b[x1][y1] += c;
b[x2 + 1][y1] -= c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y2 + 1] += c;
}
int main()
{
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
//b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1]; // 初始化差分数组
modify(i, j, i, j, a[i][j]); // 初始化差分数组
}
while (q--)
{
int x1, y1, x2, y2, c;
cin >> x1 >> y1 >> x2 >> y2 >> c;
modify(x1, y1, x2, y2, c);
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1]; // 求前缀和
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
cout << b[i][j] << ' ';
cout << endl;
}
return 0;
}
标签:y2,int,基础,cin,差分,算法,y1,x1
From: https://www.cnblogs.com/yhgm/p/18050606