A - Going Home
A - Going Home
https://vjudge.net/contest/385979#problem
0到所有🐎,🐎到🏠,房子到cnt+1连边,其中🐎和🏠的代价为曼哈顿距离
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 100010 #define For(i,a,b) for(long long i=a;i<=b;i++) #define p(a) putchar(a) #define g() getchar() using namespace std; long long n,m,s,t,x,y,v,w,maxflow,mincost,tot,cnt; long long head[N],pre[N],last[N],flow[N],d[N]; bool vis[N]; char c[510][510]; struct node{ long long n; long long v; long long w; long long next; }e[N]; struct Node{ long long x; long long y; }a[N]; queue<long long>q; void in(long long &x){ long long y=1; char c=g();x=0; while(c<'0'||c>'9'){ if(c=='-')y=-1; c=g(); } while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=g(); } x*=y; } void o(long long x){ if(x<0){ p('-'); x=-x; } if(x>9)o(x/10); p(x%10+'0'); } void push(long long x,long long y,long long v,long long w){ e[tot].n=y; e[tot].v=v; e[tot].w=w; e[tot].next=head[x]; head[x]=tot++; } bool spfa(long long s,long long t){ memset(d,0x7f,sizeof(d)); memset(flow,0x7f,sizeof(flow)); memset(vis,0,sizeof(vis)); q.push(s); vis[s]=1; d[s]=0; pre[t]=-1; while(!q.empty()){ long long now=q.front(); q.pop(); vis[now]=0; for(long long i=head[now];i!=-1;i=e[i].next) if(e[i].v>0&&d[e[i].n]>d[now]+e[i].w){ d[e[i].n]=d[now]+e[i].w; pre[e[i].n]=now; last[e[i].n]=i; flow[e[i].n]=min(flow[now],e[i].v); if(!vis[e[i].n]){ vis[e[i].n]=1; q.push(e[i].n); } } } return pre[t]!=-1; } void MCMF(long long s,long long t){ maxflow=mincost=0; while(spfa(s,t)){ long long now=t; maxflow+=flow[t]; mincost+=flow[t]*d[t]; while(now!=s){ e[last[now]].v-=flow[t]; e[last[now]^1].v+=flow[t]; now=pre[now]; } } } long long Abs(long long x){ return x>0?x:-x; } signed main(){ while(cin>>n>>m && (n+m)){ memset(head,-1,sizeof(head)); cnt=tot=0; For(i,1,n){ For(j,1,m){ cin>>c[i][j]; if(c[i][j]=='m'){ a[++cnt].x=i; a[cnt].y=j; } } } For(i,1,n){ For(j,1,m){ if(c[i][j]=='H'){ a[++cnt].x=i; a[cnt].y=j; } } } For(i,1,cnt/2){ push(0,i,1,0); push(i,0,0,0); push(i+cnt/2,cnt+1,1,0); push(cnt+1,i+cnt/2,0,0); } For(i,1,cnt/2) For(j,cnt/2+1,cnt){ long long temp=Abs(a[i].x-a[j].x)+Abs(a[i].y-a[j].y); push(i,j,1,temp); push(j,i,0,-temp); } MCMF(0,cnt+1); o(mincost);p('\n'); } return 0; }