P17066 Bridge 题解
场切的最难题,纪念一下。
我们称形如
扩展一下,对于最靠近任意一个
这下我们可以快速判断横边是否为桥了。接下来是竖边。设存在竖边
综上所述,我们需要维护所有的竖边和快速求区间横边数量。分别用
set<int>s;
int getL(int x){ // 找到左侧最近竖边
auto it=s.lower_bound(x);--it;
return *it;
}
int getR(int x){ // 找到右侧最近竖边
auto it=s.upper_bound(x);
return *it;
}
int query1(int x){ // 查询 x 所代表的竖边是否为桥边
if(x==1||x==n)return 0;
int L=getL(x),R=getR(x);
if(!query_bit(L,x-1))return 0;
if(!query_bit(x,R-1))return 0;
return 1; // 当且仅当 [L,x],[x,R] 中不含横边断边才不会成环
}
int query2(int l,int r){ // 查区间 [L,R] 中的桥边数量,包括所有横边竖边
int res=0;
res+=query1(l); // 别忘记加上竖边贡献
res+=query1(r);
if(query_bit(l,r-1))res+=(r-l)*2-1;
return res;
}
void solve(){
n=read()+2,m=read(); // 加 0 和 n+1 两个虚拟竖边特殊点,防止查 s 时越界报错
init_bit();
add_bit(1,1),add_bit(n-1,1); // 连通 (0,1) 和 (n,n+1) 横边
s.clear();
REP(i,1,n)s.insert(i);
int res=0; // 答案
REP(i,1,m){
int tp=read(),x1=read(),y1=read()+1,x2=read(),y2=read()+1;
if(y1>y2)swap(y1,y2);
int L=getL(y2),R=getR(y1);
if(tp==1){ // 加边
if(x1==x2){ // 加横边,会影响一个极小区间
res-=query2(L,R);
add_bit(y1,1);
res+=query2(L,R);
}else{ // 加竖边,会影响两个左右极小区间
res-=query2(L,R);
s.insert(y1);
res+=query2(L,y1);
res+=query2(y1,R);
res-=query1(y1);
}
}else{ // 断边,反之同理
if(x1==x2){
res-=query2(L,R);
add_bit(y1,-1);
res+=query2(L,R);
}else{
res-=query2(L,y1);
res-=query2(y1,R);
res+=query1(y1);
s.erase(s.find(y1));
res+=query2(L,R);
}
}
writeln(res);
}
}