bzoj:3171: [Tjoi2013]循环格
原题链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3171
感觉构图的方法还是很巧妙的。每个格子拆出点入点,分别连到源汇,然后相邻的格子再连一波,其实也是利用了每个格子出度入度均为1。
拉个模版下来都能套错……
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<queue> #include<cstdio> #include<cstring> #include<algorithm> #define MAXN 21000 #define MAXM 12000 using namespace std; struct na{ int y,z,f,ne; }b[MAXM]; int n,m,l[MAXN],r[MAXN],num=1,p,ch,ans=0,S,T,k,dis[MAXN],an=0,mi[MAXN],ro[MAXN],qi[MAXN],a,d,fa,fb,f,v; bool bo[MAXN]; const int INF=1e9; queue <int> q; inline int min(int x,int y){return x>y?y:x;} inline int read(){ p=0;ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') p=p*10+ch-48, ch=getchar(); return p; } char s[20]; inline void spfa(){ register int i; q.push(S); bo[S]=1; for (i=0;i<=T;i++) dis[i]=INF,mi[i]=0; mi[S]=INF;dis[S]=0; while(!q.empty()){ int k=q.front();q.pop();bo[k]=0; if (k==T) continue; for (i=l[k];i;i=b[i].ne) if (b[i].z>0&&dis[b[i].y]>b[i].f+dis[k]){ dis[b[i].y]=b[i].f+dis[k]; mi[b[i].y]=min(mi[k],b[i].z); ro[b[i].y]=i; qi[b[i].y]=k; if (!bo[b[i].y]){ bo[b[i].y]=1; q.push(b[i].y); } } } } inline int add(int x,int y,int z,int f){ num++; if (l[x]==0) l[x]=num;else b[r[x]].ne=num; b[num].y=y;b[num].z=z;b[num].f=f;r[x]=num; } inline void in(int x,int y,int z,int f){/*printf("%d %d %d %d\n",x,y,z,f);*/add(x,y,z,f),add(y,x,0,-f);} int main(){ //freopen("a.in","r",stdin); //freopen("a.out","w",stdout); register int i,j; n=read();m=read();S=n*m*2;T=n*m*2+1; for (i=0;i<n;i++) for (scanf("%s",s),j=0;j<m;j++){ in(S,i*m+j,1,0); in(i*m+j+n*m,T,1,0); in(i*m+j,(i+1)%n*m+j+n*m,1,s[j]!='D'); in(i*m+j,(i+n-1)%n*m+j+n*m,1,s[j]!='U'); in(i*m+j,i*m+(j+1)%m+n*m,1,s[j]!='R'); in(i*m+j,i*m+(j+m-1)%m+n*m,1,s[j]!='L'); } for(;;){ spfa(); if (dis[T]==INF) break; an+=mi[T]*dis[T]; for (i=T;i!=S;i=qi[i]) b[ro[i]].z-=mi[T],b[ro[i]^1].z+=mi[T]; } printf("%d\n",an); }