跳到正文

题解

P17066 Bridge 题解

Rosabel约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年7月6日
收录
2026年8月20日
更新
2026年8月20日
篇幅
约 4 分钟
获赞
1
题目
P17066

版本

  1. v1当前

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

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

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

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

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

C++
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);
	}
}
原文