ABC477F 扫描线(BIT 二维数点)+前缀和
背景
吃了 BC 罚时,然后 E 想到 Dijkstra,分类讨论后却忘了可以跑最短路,于是有半个小时想偏了,还有救吗……
反正没时间看 F。
本题解适合想要保留部分独立思考的选手。这是我的折叠框写法 V3。
正文
::::info[Hint 1 观察] 观察题目,每次给定一个窗口,然后统计其中有多少个黑格子。
| 这像什么问题呢? |
|---|
::::success[Solution 1] 可以发现这题非常适合用扫描线解决。我们将其转换为一个类似二维数点的问题。
| 具体地,把每个查询窗口拆成四个角,分别存进结构体,并按行号排序。 |
|---|
::::info[Hint 2 转换] 但是题目每次是把一个区间变为黑格子,这种怎么处理呢? ::::
::::success[Solution 2-1] 首先,当然可以把正常二位数点问题的差分 BIT 变为差分线段树,但是我们还有第二个办法。 ::::
::::success[Solution 2-2]
观察到,如果我们只进行一次差分:若每一行
| 而题目要求的是前 |
|---|
::::info[Hint 3 推导] 但是如何用树状数组维护前缀和的前缀和呢?
设差分数组
规定以下变量:
-
-
-
::::
::::success[Solution 3] 非常详细的解释可以看这里。
一次前缀和得到每列的覆盖次数,二次前缀和才是前
由定义:
交换求和顺序:固定
把系数拆开:
因此,我们只需要维护两个一次前缀和:
-
\sum_{k=1}^{y}d[k] -
\sum_{k=1}^{y}k\cdot d[k]
| 分别用树状数组 |
|---|
::::warning[实现细节]
在 update 函数中,同时修改
查询时,前
(pt[nw].y + 1) * query(tr1, pt[nw].y) - query(tr2, pt[nw].y)
注意点:
- 窗口四个角要按照二维前缀和的容斥拆法,而不是直接放坐标。
- 当点坐标
x 为0 的时候需要跳过(此时前缀和为0 )。 -
-
十年 OI 一场空,不开 long long见祖宗。
::::success[AC Code]
#include<iostream>
#include<algorithm>
#define LL long long
#define F(i,k,n) for(int i=(k);i<=(n);++i)
#define RF(i,k,n) for(int i=(k);i>=(n);--i)
using namespace std;
LL ans[200005];
struct LN{
int l,r;
}ln[200005];
struct PT{
int x;
int y;
int s;
int id;
}pt[800005];
int tot=0;
LL tr1[200005];
LL tr2[200005];
int lowbit(int x){
return x&-x;
}
void update(int x,LL y){
int p=x;
while(x<=200000){
tr1[x]+=y;
tr2[x]+=y*p;
x+=lowbit(x);
}
return;
}
LL query(LL tr[],int x){
LL sum=0;
while(x>0){
sum+=tr[x];
x-=lowbit(x);
}
return sum;
}
bool cmp(PT a,PT b){
return a.x<b.x;
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n,m,q;
cin>>n>>m>>q;
F(i,1,n){
cin>>ln[i].l>>ln[i].r;
}
F(i,1,q){
int a,b,c,d;
cin>>a>>b>>c>>d;
--a,--c;
pt[++tot].x=a;
pt[tot].y=c;
pt[tot].s=1;
pt[tot].id=i;
pt[++tot].x=a;
pt[tot].y=d;
pt[tot].s=-1;
pt[tot].id=i;
pt[++tot].x=b;
pt[tot].y=c;
pt[tot].s=-1;
pt[tot].id=i;
pt[++tot].x=b;
pt[tot].y=d;
pt[tot].s=1;
pt[tot].id=i;
}
//cout<<"tot"<<tot<<'\n';
sort(pt+1,pt+tot+1,cmp);
int nw=0;
while(nw<tot&&pt[nw+1].x==0){
++nw;
}
F(i,1,n){
update(ln[i].l,1);
update(ln[i].r+1,-1);
while(nw<tot&&pt[nw+1].x==i){
++nw;
ans[pt[nw].id]+=((pt[nw].y+1)*query(tr1,pt[nw].y)-query(tr2,pt[nw].y))*pt[nw].s;
//cout<<"pt"<<pt[nw].x<<' '<<pt[nw].y<<' '<<query(pt[nw].y)<<' '<<query(pt[nw].y)*pt[nw].s<<'\n';
}
}
F(i,1,q){
cout<<ans[i]<<'\n';
}
return 0;
}
/*
3 6 3
2 4
1 1
4 6
1 2 1 4
2 3 3 6
1 1 5 6
*/
| 提交记录。 |
|---|
附记
预期难度:下位青(二维数点升级版)。
AI:本文部分 LaTeX 和语言经过 DeepSleep 处理。