poj2195
来源:互联网 发布:高速公路机电系统优化 编辑:程序博客网 时间:2024/05/24 01:22
链接:点击打开链接
题意:在一个矩阵中,有一些人和房子('m'代表人,'H'代表房子),每个房子中要安排一个人,每个人移动一步需要1美元,求为每个人安排房子后所需要的金钱的最小值
代码:
#include <math.h>#include <vector>#include <stdio.h>#include <stdlib.h>#include <iostream>#include <algorithm>using namespace std;const int INF=0x3f3f3f3f;struct node{ int to,cap,cost,rev;};int V;int dis[10005],prevv[10005],preve[10005];vector<node> G[10005];void addedge(int from,int to,int cap,int cost){ G[from].push_back((node){to,cap,cost,G[to].size()}); G[to].push_back((node){from,0,-cost,G[from].size()-1});}int min_cost_flow(int s,int t,int f){ int i,d,v,ans,sign; ans=0; while(f>0){ fill(dis,dis+V,INF); dis[s]=0; sign=1; while(sign){ sign=0; for(v=0;v<V;v++){ if(dis[v]==INF) continue; for(i=0;i<G[v].size();i++){ node &e=G[v][i]; if(e.cap>0&&dis[e.to]>dis[v]+e.cost){ dis[e.to]=dis[v]+e.cost; prevv[e.to]=v; preve[e.to]=i; sign=1; } } } } if(dis[t]==INF) return -1; d=f; for(v=t;v!=s;v=prevv[v]) d=min(d,G[prevv[v]][preve[v]].cap); f-=d; ans+=d*dis[t]; for(v=t;v!=s;v=prevv[v]){ node &e=G[prevv[v]][preve[v]]; e.cap-=d; G[v][e.rev].cap+=d; } } return ans;} //费用流模板char s[505][505];struct nod{ int x,y;};vector<nod> v1,v2;int main(){ int n,m,i,j,tmp,tmp1,tmp2; while(scanf("%d%d",&n,&m)!=EOF&&(n||m)){ v1.clear(),v2.clear(); for(i=0;i<=n*m+1;i++) G[i].clear(); for(i=1;i<=n;i++){ getchar(); for(j=1;j<=m;j++){ scanf("%c",&s[i][j]); if(s[i][j]=='m') v1.push_back((nod){i,j}); else if(s[i][j]=='H') v2.push_back((nod){i,j}); } } //找出所有的人和房子 tmp1=v1.size(),tmp2=v2.size(); V=tmp1+tmp2+2; for(i=1;i<=tmp1;i++) addedge(0,i,1,0); for(i=tmp1+1;i<V;i++) addedge(i,V-1,1,0); //与源点和汇点相连的边容量为1,费用为0 for(i=0;i<tmp1;i++) for(j=0;j<tmp2;j++){ tmp=abs(v1[i].x-v2[j].x)+abs(v1[i].y-v2[j].y); addedge(i+1,j+tmp1+1,1,tmp); //容量为1,费用为曼哈顿距离 } //求流量是tmp1的最小费用流 printf("%d\n",min_cost_flow(0,V-1,tmp1)); } return 0;}
0 0
- poj2195
- poj2195
- poj2195
- poj2195
- poj2195
- POJ2195 最佳匹配
- poj2195 Going Home
- poj2195 Going Home
- poj2195 - Going Home
- POJ2195--Going Home
- poj2195 Going Home
- poj2195 Going Home
- 二分图匹配 POJ2195
- poj2195(KM)
- poj2195 Going Home
- POJ2195 Going Home
- poj2195 -最小费用流
- POJ2195 Going Home
- BZOJ 1115: [POI2009]石子游戏Kam
- 【收集】Android开源库
- jboss 到oracle 数据库连接无效的问题
- mysql-5.6.27主从设置
- 自定义控件View
- poj2195
- 计算机网络高级软件编程技术
- ubuntu没有man pthread_mutex_init
- codeblock中没有gcc编译器的解决方案
- Light OJ 1193 Dice (II) (DP)
- bindService与startService
- iOS --- 根据字符串的实际大小来计算UILabel的size
- LVS的DR模式
- 多重背包转01背包/母函数(1171)