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 93 94
| const int N=2e5+10;
int n,m,d; string s[N]; int I(int x,int y){ return (x-1)*m+y; } ll ans;
vector <int> G[N]; int col(int u){ return ((u-1)%m+(u-1)/m)&1; }
void Link(int u,int v){ G[u].pb(v),ind[v]++; } int ind[N],L[N],R[N],dfn; void dfs(int u,int f){ L[u]=++dfn; for(int v:G[u]) if(v!=f) dfs(v,u); R[u]=dfn; }
struct Node{ int mi,x; Node operator + (const Node _) const { Node res; res.mi=min(mi,_.mi),res.x=0; if(mi==res.mi) res.x+=x; if(_.mi==res.mi) res.x+=_.x; return res; } } tr[N<<2]; int t[N<<2]; void Down(int p){ if(!t[p]) return; rep(i,p<<1,i+1) t[i]+=t[p],tr[i].mi+=t[p]; t[p]=0; } void Upd(int p,int l,int r,int ql,int qr,int x){ if(ql<=l && r<=qr) { t[p]+=x,tr[p].mi+=x; return; } Down(p); int mid=(l+r)>>1; if(ql<=mid) Upd(p<<1,l,mid,ql,qr,x); if(qr>mid) Upd(p<<1|1,mid+1,r,ql,qr,x); tr[p]=tr[p<<1]+tr[p<<1|1]; }
struct Update{ int p,l,r,x; bool operator < (const Update __) const { return p<__.p; } } U[N*2]; int C;
void Add(int x,int y){ if(col(x)) swap(x,y); U[++C]=(Update){L[x],L[y],R[y],1}; U[++C]=(Update){R[x]+1,L[y],R[y],-1}; } void Build(int p,int l,int r){ tr[p]=(Node){0,r-l+1}; if(l==r) return; int mid=(l+r)>>1; Build(p<<1,l,mid),Build(p<<1|1,mid+1,r); }
int main(){ n=rd(),m=rd(); rep(i,1,n) { cin>>s[i]; rep(j,1,m) { if(s[i][j-1]=='U') if(i>1) Link(I(i-1,j),I(i+1,j)); if(s[i][j-1]=='D') if(i<n) Link(I(i+1,j),I(i-1,j)); if(s[i][j-1]=='L') if(j>1) Link(I(i,j-1),I(i,j+1)); if(s[i][j-1]=='R') if(j<m) Link(I(i,j+1),I(i,j-1)); } } rep(i,1,n*m) if(!ind[i]) dfs(i,0); rep(i,1,n) { rep(j,1,m) { if(s[i][j-1]=='U') Add(I(i,j),I(i+1,j)); if(s[i][j-1]=='L') Add(I(i,j),I(i,j+1)); } } Build(1,1,dfn); sort(U+1,U+C+1); int p=1; rep(i,1,dfn) { while(p<=C && U[p].p<=i) Upd(1,1,dfn,U[p].l,U[p].r,U[p].x),p++; int c=dfn-(tr[1].mi==0?tr[1].x:0); ans+=c; } printf("%lld\n",ans); }
|