POJ-2159 最小费用最大流
来源:互联网 发布:朗诗地产北京公司知乎 编辑:程序博客网 时间:2024/06/09 23:24
Going Home
自己写的第一道费用流,图建好一波板子AC。不过还是有几个地方有点迷。
先来看看思想:题意是平面图上每个点有若干个人和若干个房子,保证人的数量等于房子的数量。每个格子上可以同时容纳所有人,也允许一个人在一个房子的格子上但不进入房子。求所有人都找到一个房子住所走的距离的和的最小值。
典型的最小费用最大流问题,用0点作为源点,给人编号,然后从源点引入一条边连接人,容量为1,费用为0,给房子编号,每个人到每个房子连一条边,容量为1,费用为他们的曼哈顿距离。然后再设置一个点作为汇点,所有的房子都与汇点连一条边,容量为1,费用为0.求一遍最小费用流就行了。
const int N=1e5+10;struct Edge{ int to,next,cap,flow,cost;} e[N*10];int head[N],tot;int pre[N],dis[N];int vis[N],Vis[201][201];int n,m,tn;char s[201][201];void init(int num){ tot=0;//边的数量 tn=num; memset(head,-1,sizeof(head));}void add(int u,int v,int cap,int cost){ e[tot].to=v,e[tot].cap=cap,e[tot].cost=cost,e[tot].flow=0; e[tot].next=head[u]; head[u]=tot++; e[tot].to=u,e[tot].cap=0,e[tot].cost=-cost,e[tot].flow=0; e[tot].next=head[v]; head[v]=tot++;}bool spfa(int s,int t){ queue<int>q; for(int i=0; i<=tn; i++) { dis[i]=INF; vis[i]=0; pre[i]=-1; } dis[s]=0; vis[s]=1; q.push(s); while(!q.empty()) { int u=q.front(); q.pop(); vis[u]=0; for(int i=head[u]; i+1; i=e[i].next) { int v=e[i].to; if(e[i].cap>e[i].flow&&dis[v]>dis[u]+e[i].cost) { dis[v]=dis[u]+e[i].cost; pre[v]=i; if(!vis[v]) { vis[v]=1; q.push(v); } } } } if(pre[t]==-1) return false; return true;}int mincost_maxflow(int s,int t){ int cost=0; while(spfa(s,t)) { int Min=INF; for(int i=pre[t]; i!=-1; i=pre[e[i^1].to]) if(Min>e[i].cap-e[i].flow) Min=e[i].cap-e[i].flow; for(int i=pre[t]; i!=-1; i=pre[e[i^1].to]) { e[i].flow+=Min; e[i^1].flow-=Min; cost+=e[i].cost*Min; } } return cost;}struct node{ int x,y;};vector<node>M,H;int main(){ while(~scanf("%d%d",&n,&m)) { if(n==0&&m==0) return 0; M.clear(); H.clear(); int num=1,tmp=1; for(int i=0; i<n; i++) { scanf("%s",s[i]); for(int j=0; j<m; j++) if(s[i][j]!='.') tmp++; } init(tmp); for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(s[i][j]!='.') { if(s[i][j]=='m') { add(0,num,1,0);//0为源点; M.push_back(node {i,j}); } else { add(num,tmp,1,0);//m+h+1为汇点 H.push_back(node {i,j}); } Vis[i][j]=num++; } for(int i=0; i<M.size(); i++) { node tmpM=M[i]; for(int j=0; j<H.size(); j++) { node tmpH=H[j]; int diss=abs(tmpM.x-tmpH.x)+abs(tmpM.y-tmpH.y); add(Vis[tmpM.x][tmpM.y],Vis[tmpH.x][tmpH.y],1,diss); } } printf("%d\n",mincost_maxflow(0,tmp)); } return 0;}
阅读全文
0 0
- poj 2159(最小费用最大流)
- POJ-2159 最小费用最大流
- POJ 2159 Going Home 网络流 最小费用最大流
- POJ 2159 Going Home 网络流 最小费用最大流
- 最小费用最大流模板 poj 2159 模板水题
- poj 2159 Going Home 最小费用最大流
- poj 2516 最小费用最大流
- poj/pku 3680(最小费用最大流)
- 【最小费用最大流】POJ 2516【unsolved】
- 【最小费用最大流】POJ 2195
- POJ 2135 最小费用最大流
- poj 2195 最小费用最大流
- POJ 3680 最小费用最大流
- POJ 2516(最小费用最大流)
- poj 2195 (最小费用最大流)
- poj 2135 最小费用最大流
- poj 2195 最小费用最大流
- POJ 3686 最小费用最大流
- 爬取糗事百科
- 整数区间(贪心)
- Swift3.0之String转换成基本数据类型 Int CGFloat Double
- 新手向解密加密后的dll 提取dll 适用于简单加密后的apk
- CodeForces
- POJ-2159 最小费用最大流
- Shell输入输出重定向~11
- Eclipse最实用快捷键
- 五.Core组件进阶(3.访问图像中的像素点)
- Android四大组件之一:广播
- MATLAB数据类型
- RCTEventEmitter使用
- Linux 内核
- 计算机软件配置项(转)