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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include<bits/stdc++.h> #define int long long #define ull unsigned long long #define maxn 5005 #define put() putchar('\n') #define Tp template<typename T> #define Ts template<typename T,typename... Ar> using namespace std; Tp void read(T &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; #define fi first #define se second #define mk make_pair const int mod=1e9+7; int power(int x,int y=mod-2) { int sum=1; while (y) { if (y&1) sum=sum*x%mod; x=x*x%mod;y>>=1; } return sum; } int head=1,h[maxn]; struct yyy { int to,z,w,val; void add(int x,int y,int W,int V) { to=y;z=h[x];h[x]=head;w=W;val=V; } }a[100005]; void ins(int x,int y,int z,int val) { a[++head].add(x,y,z,val); a[++head].add(y,x,0,-val); } int s,t,n,m; int ans,anss; const int inf=1e9; namespace Dinic { int vis[maxn],dis[maxn],now[maxn]; queue<int>q; bool spfa(void) { memset(dis,0x3f,sizeof(dis)); memcpy(now,h,sizeof(now)); int i,x; q.push(s);dis[s]=0; while (!q.empty()) { x=q.front();q.pop(); for (i=h[x];i;i=a[i].z) if (a[i].w&&dis[a[i].to]>dis[x]+a[i].val) { dis[a[i].to]=dis[x]+a[i].val; q.push(a[i].to); } } return dis[t]<=inf; } int anss,ans; int dfs(int x,int in) { if (x==t||!in) return anss+=in*dis[t],ans+=in,in; vis[x]=1; int i,sum=0,res=in; for (i=now[x];i&&res;i=a[i].z) { now[x]=i; if (!vis[a[i].to]&&dis[a[i].to]==dis[x]+a[i].val&&a[i].w) { sum=dfs(a[i].to,min(res,a[i].w)); a[i].w-=sum,res-=sum,a[i^1].w+=sum; } } vis[x]=0; return in-res; } pair<int,int> dinic(void) { while (spfa()) dfs(s,inf); return mk(ans,anss); } } int fx[5]={0,-1,1,0,0}; int fy[5]={0,0,0,-1,1}; int id(int i,int j) { if (i==0) i=n; if (i==n+1) i=1; if (j==0) j=m; if (j==m+1) j=1; return (i-1)*m+j; } signed main(void){ int i,j,k,x,y,z,val;char ch; read(n);read(m); s=0;t=n*m*2+1; for (i=1;i<=n;i++) { for (j=1;j<=m;j++) { cin>>ch;int op=0; if (ch=='U') op=1; else if (ch=='D') op=2; else if (ch=='L') op=3; else op=4; ins(s,id(i,j),1,0); ins(id(i,j)+n*m,t,1,0); for (k=1;k<=4;k++) ins(id(i,j),id(i+fx[k],j+fy[k])+n*m,1,(k!=op)); } } auto tmp=Dinic::dinic(); gdb(tmp.fi); printf("%lld\n",tmp.se); return 0; }
|