1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include<algorithm> #include<cstring> #include<cstdio> #include<vector> #include<queue> #include<map> #define inf 0x3f3f3f3f3f3f3f3fll using namespace std; using ll=long long; using pli=pair<ll,int>; using pi=pair<int,int>; template<typename A> using vc=vector<A>; inline int read() { int s=0,w=1;char ch; while((ch=getchar())>'9'||ch<'0') if(ch=='-') w=-1; while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); return s*w; } int fa[2000001][23]; char in[1002][1002]; int pre[1002][1002]; int ma[1001][1001]; int dep[2000001]; int w[2000001]; int f[2000001]; vc<pi>a[1001]; int cnt; int n,q; inline int getma(int x,int y) { if(in[x][y]=='#') return 0; int ans=0; for(int i=512;i;i>>=1) if(x-i-ans>=1&&x+i+ans<=n&&y-i-ans>=1&&y+i+ans<=n&& pre[x+i+ans][y+i+ans]-pre[x+i+ans][y-i-ans-1]-pre[x-i-ans-1][y+i+ans]+pre[x-i-ans-1][y-i-ans-1]==0) ans+=i; return ans*2+1; } inline int id(int x,int y) { return (x-1)*n+y; } inline int find(int num) { if(f[num]==num) return num; return f[num]=find(f[num]); } inline int get(int u,int v) { if(dep[u]<dep[v]) swap(u,v); for(int i=20;i>=0;i--) if(dep[u]-(1<<i)>=dep[v]) u=fa[u][i]; if(u==v) return w[v]; for(int i=20;i>=0;i--) if(fa[u][i]!=fa[v][i]) u=fa[u][i],v=fa[v][i]; return w[fa[u][0]]; } int main() { n=read(); for(int i=1;i<=n;i++) { scanf("%s",in[i]+1); for(int j=1;j<=n;j++) pre[i][j]=pre[i-1][j]+pre[i][j-1]-pre[i-1][j-1]+(in[i][j]=='#'); } q=read();cnt=n*n; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) w[id(i,j)]=ma[i][j]=getma(i,j); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { if(i<n) a[min(ma[i][j],ma[i+1][j])].push_back(pi(id(i,j),id(i+1,j))); if(j<n) a[min(ma[i][j],ma[i][j+1])].push_back(pi(id(i,j),id(i,j+1))); } for(int i=1;i<=cnt;i++) f[i]=i; for(int i=n;i>=0;i--) for(pi j:a[i]) { int u=find(j.first),v=find(j.second); if(u==v) continue; cnt++,f[u]=f[v]=f[cnt]=cnt; fa[u][0]=fa[v][0]=cnt; w[cnt]=i; } for(int i=cnt-1;i;i--) { dep[i]=dep[fa[i][0]]+1; for(int j=0;fa[fa[i][j]][j];j++) fa[i][j+1]=fa[fa[i][j]][j]; } for(int i=1;i<=q;i++) { int xa=read(),ya=read(),xb=read(),yb=read(); printf("%d\n",get(id(xa,ya),id(xb,yb))); } return 0; }
|