对二维前缀和的离线处理——2019南京网络赛A
二维前缀和
正常来说,我们处理二维前缀和需要开一个二维数组a[N][N],然后对于覆盖区间(x1, y1)(左下角)到(x2, y2)(右上角)
a[x1−1][y1−1]++;
a[x1−1][y2]−−;
a[x2][y1−1]−−;
a[x2][y2]++;
然后我们在前缀和
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
如果我们要查询(x1, y1)到(x2, y2)
a[x2][y2]−a[x2][y1−1]−a[x1−1][y2]+a[x1−1][y1−1]
对于n<= 1000以内,还是很方便的,但是当n的量级为1e5,我们就无法处理了
使用树状数组离线处理二维前缀和(处理二维偏序)
我们知道树状数组可以维护前缀和,然后我们将x,y的任意一维用树状数组维护,对另一维进行滚动压缩处理,其中我们将一个查询区间拆成四个点(本次是对y滚动压缩)
详情看代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6 + 5;
struct point
{
ll x, y, w;
point(ll _x = 0,ll _y = 0, ll _w = 1) : x(_x), y(_y), w(_w) {}
bool operator < (const point a) const
{
return y < a.y;
}
}p[N];
struct node
{
ll x, y, id, flag;
node(ll _x = 0, ll _y = 0, ll _id = 0, ll _flag = 0) : x(_x), y(_y), id(_id), flag(_flag) {} bool operator < (const node a) const
{
return y < a.y;
}
}Interval[N << 2];
ll n, m, q, tot;
ll sum[N], ans[N];
ll get_nusum(ll x)
{
ll tmp = 0;
while(x)
tmp += x % 10, x /= 10;
return tmp;
}
ll get_val(ll x, ll y)//螺旋矩阵
{
ll q = min(x, min(y, min(n - x + 1, n - y + 1)));
ll ans;
ll tmpx = x, tmpy = y;
x = n - tmpy + 1;
y = n - tmpx + 1;
swap(x, y);
if(x <= y)
ans = q * (4 * (n - 1) - 4 * q) + 10 * q - 4 * n - 3 + x + y;
else
ans = q * (4 * n - 4 * q) - x - y + 2 * q + 1;
return get_nusum(ans);
}
ll lowbit(ll x)
{
return x & (-x);
}
void insert(ll x, ll val)
{
for(ll i = x; i <= n; i += lowbit(i))
sum[i] += val;
}
ll query(ll x)
{
ll ans = 0;
for(ll i = x; i; i -= lowbit(i))
ans += sum[i];
return ans;
}
void solve()//对y排序滚动,树状数组维护x
{
ll pos = 1;
for(int i = 1; i <= tot; i ++)
{
while(pos <= m && p[pos].y <= Interval[i].y)
{
insert(p[pos].x, p[pos].w);
pos ++;
}
ans[Interval[i].id] += query(Interval[i].x) * Interval[i].flag;
}
}
int main()
{
int t;
cin >> t;
while(t --)
{
scanf("%lld%lld%lld", &n, &m, &q);
tot = 0;
memset(sum, 0, sizeof(sum));
memset(ans, 0, sizeof(ans));
for(int i = 1; i <= m; i ++)
{
ll x, y;
scanf("%lld%lld", &x, &y);
p[i] = point(x, y, get_val(x, y));
}
sort(p + 1, p + m + 1);
for(int i = 1; i <= q; i ++)//q次询问,离线操作
{
ll x1, x2, y1, y2;
scanf("%lld%lld%lld%lld", &x1, &y1, &x2, &y2);//拆点,处理二维前缀和
Interval[++ tot] = node(x1 - 1, y1 - 1, i, 1);
Interval[++ tot] = node(x1 - 1, y2, i, - 1);
Interval[++ tot] = node(x2, y1 - 1, i, - 1);
Interval[++ tot] = node(x2, y2, i, 1);
}
sort(Interval + 1, Interval + 1 + tot);
solve();
for(int i = 1; i <= q; i ++)
printf("%lld\n", max(1ll * 0, ans[i]));
}
}