P17066 Bridge 题解

· · 题解

场切的最难题,纪念一下。

我们称形如 (x,y)-(x,y+1) 的边为 横边,形如 (0,y)-(1,y) 的边为 竖边。不难发现如果在 (y,y+1) 之间的两条竖边有一条断掉了,那么另外一条必然为桥。

扩展一下,对于最靠近任意一个 y 左边的横边 L 和最靠近 y+1 右边的横边 R 所代表的区间 [L,R] 中的所有横边,断边的数量最多只能有一条,否则图不连通。当断边数为 0 时,所有边都不是桥边,因为会成一个 [L,R] 环;当断边数为 1 时,桥边的数量为 2(R-L)-1。

这下我们可以快速判断横边是否为桥了。接下来是竖边。设存在竖边 x,靠近的最左、右竖边分别为 L,R,那么竖边 x 为桥边的充要条件是 [L,x] 和 [x,R] 中的所有横边中各有一条是断边,否则成环就不是桥边了。

综上所述,我们需要维护所有的竖边和快速求区间横边数量。分别用 \text{set} 和 \text{Fenwick Tree} 维护即可。

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);
    }
}