标签:mat step grid search term input head ges send
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 22088 | Accepted: 11155 |
Description
Input
Output
Sample Input
2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
Sample Output
2 10 28
Source
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; typedef long long ll; const int N=5005,M=1e6+5,INF=1e9; int read(){ char c=getchar();int x=0,f=1; while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1; c=getchar();} while(c>=‘0‘&&c<=‘9‘){x=x*10+c-‘0‘; c=getchar();} return x*f; } int n,m,s,t,n1,n2; char ss[105]; struct data{ int x,y; }a[N],b[N]; inline int dis(data &a,data &b){return abs(a.x-b.x)+abs(a.y-b.y);} struct edge{ int v,ne,c,f,w; }e[M<<1]; int cnt,h[N]; inline void ins(int u,int v,int c,int w){ cnt++; e[cnt].v=v;e[cnt].c=c;e[cnt].f=0;e[cnt].w=w; e[cnt].ne=h[u];h[u]=cnt; cnt++; e[cnt].v=u;e[cnt].c=0;e[cnt].f=0;e[cnt].w=-w; e[cnt].ne=h[v];h[v]=cnt; } void build(){ cnt=0; memset(h,0,sizeof(h)); s=0;t=n1+n2+1; for(int i=1;i<=n1;i++) for(int j=1;j<=n2;j++) ins(i,n1+j,1,dis(a[i],b[j])); for(int i=1;i<=n1;i++) ins(s,i,1,0); for(int i=1;i<=n2;i++) ins(n1+i,t,1,0); } int d[N],q[N],head,tail,inq[N],pre[N],pos[N]; inline void lop(int &x){if(x==N)x=1;} bool spfa(){ memset(d,127,sizeof(d)); memset(inq,0,sizeof(inq)); head=tail=1; d[s]=0;inq[s]=1;q[tail++]=s; pre[t]=-1; while(head!=tail){ int u=q[head++];inq[u]=0;lop(head); for(int i=h[u];i;i=e[i].ne){ int v=e[i].v,w=e[i].w; if(d[v]>d[u]+w&&e[i].c>e[i].f){ d[v]=d[u]+w; pre[v]=u;pos[v]=i; if(!inq[v])q[tail++]=v,inq[v]=1,lop(tail); } } } return pre[t]!=-1; } int mcmf(){ int flow=0,cost=0; while(spfa()){ int f=INF; for(int i=t;i!=s;i=pre[i]) f=min(f,e[pos[i]].c-e[pos[i]].f); flow+=f;cost+=d[t]*f; for(int i=t;i!=s;i=pre[i]){ e[pos[i]].f+=f; e[((pos[i]-1)^1)+1].f-=f; } } return cost; } int main(int argc, const char * argv[]){ while(true){ n1=n2=0; n=read();m=read(); if(n==0&&m==0) break; for(int i=1;i<=n;i++){ scanf("%s",ss+1); for(int j=1;j<=m;j++){ if(ss[j]==‘H‘) a[++n1]=(data){i,j}; if(ss[j]==‘m‘) b[++n2]=(data){i,j}; } } build(); printf("%d\n",mcmf()); } }
POJ2195 Going Home[费用流|二分图最大权匹配]
标签:mat step grid search term input head ges send
原文地址:http://www.cnblogs.com/candy99/p/6127049.html