跳到正文

题解

题解:P7462 [CERC2018] Shooter Island

RaizCuadrada约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年9月21日
收录
2026年11月6日
更新
2026年11月11日
篇幅
约 5 分钟
获赞
1
题目
P7462

版本

  1. v1当前

做完这道题会对并查集有新的理解。

思路

离线处理+并查集。

其实我们不需要管船的半径,因为这样一定过不去两个格子顶点中间的缝隙,可以将它抽象为一个点,则题目与以下等价:

操作 00:每次给出一个矩形,要求将矩形激活。

操作 11:给出两个坐标,判断是否在一个四连通块中。

因为每次暴力操作修改矩形会 TLE,我们可以想到,每个格子有且仅有一次激活,并且注意到 x1,x2≤50x_1,x_2\le 50 的范围,可以想到逐行操作。

我们设 nxtx,ynxt_{x,y} 表示在 (x,y)(x,y) 坐标所在行,大于等于 yy 的第一个未激活位置,fx,yf_{x,y} 表示 (x,y)(x,y) 所在连通块的根,两者均可以使用并查集维护。

因为 ff 数组我不想用 pair,所以我使用压缩的方法,即对于 (x,y)(x,y),他的序号 id=(x−1)×N+yid=(x-1)\times N+y 其中 NN 为列数。

则解码 x=idN+1,y≡id(modN)x=\frac{id}{N+1},y\equiv id\pmod{N},因为在 y=Ny=N 时 xx 会多一个,yy 会变成 00,且在上文中的 nxtnxt 当全填满时,第一个未填的位置正好变成 N+1N+1,所以我们设 N=105+1N=10^5+1。

因为每个格子有且仅有一次激活,所以最多只会将所有格子操作一遍,且并查集复杂度可以做到 α(N)\alpha(N),因此总复杂度为 O(NMα(N))O(NM\alpha(N)),MM 为行数。

代码

C++
#include <bits/stdc++.h>
using namespace std;
const int N=100001;
int L,nxt[55][100005],f[100005*55];
struct qry{
    int t,x1,y1,x2,y2;
}q[200005];
vector<int>v[200005];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int fnxt(int x,int y){return nxt[x][y]==y?y:nxt[x][y]=fnxt(x,nxt[x][y]);}
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
int main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    for(int x=1;x<=50;x++)
        for(int y=1;y<=N;y++)
            nxt[x][y]=y;
    cin>>L;
    for(int i=1;i<=L;i++){
        int t,x1,y1,x2,y2;
        cin>>t>>x1>>y1>>x2>>y2;
        q[i]={t,x1,y1,x2,y2};
        if(!t){
            int lx=min(x1,x2),rx=max(x1,x2),uy=min(y1,y2),dy=max(y1,y2);
            for(int x=lx;x<=rx;x++){
                int y=fnxt(x,uy);
                while(y<=dy){
                    v[i].push_back((x-1)*N+y);
                    y=nxt[x][y]=fnxt(x,y+1);
                }
            }
        }
    }
    for(int i=1;i<=N*50;i++)f[i]=-1;
    for(int i=1;i<=L;i++){
        for(int u:v[i]){
            f[u]=u;
            int x=u/N+1,y=u%N;
            for(int k=0;k<4;k++){
                int xx=x+dx[k];
                int yy=y+dy[k];
                int nu=(xx-1)*N+yy;
                if(xx<1||xx>50||yy<1||yy>N||f[nu]==-1)continue;
                int fu=find(u),fnu=find(nu);
                if(fu==fnu)continue;
                f[fu]=fnu;
            }
        }
        if(q[i].t){
            int u1=(q[i].x1-1)*N+q[i].y1;
            int u2=(q[i].x2-1)*N+q[i].y2;
            if(f[u1]==-1||f[u2]==-1){
                cout<<"0\n";
                continue;
            }
            cout<<(find(u1)==find(u2)?"1":"0")<<"\n";
        }
    }
    return 0;
}

完结撒花。

原文