标签:des http os io strong for ar art
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 17975 | Accepted: 9155 |
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
比较裸的费用流,可以当做模板用,建图方式在代码中有
#include <cstdio>
#include <cstring>
#include <queue>
#include <math.h>
#include <algorithm>
using namespace std;
#define maxn 310
#define INF 0x3f3f3f3f
struct node
{
int v , w , s ;
int next ;
} p[maxn*100];
int head[maxn] , cnt , vis[maxn] , pre[maxn] , dis[maxn] ;
queue <int> q ;
struct n
{
int x , y ;
} mm[120] , hh[120] ; //mm储存人的坐标,hh存储房屋的坐标
char str[120][120] ;
void add(int u,int v,int w,int s)
{
p[cnt].v = v ; p[cnt].w = w ; p[cnt].s = s ;
p[cnt].next = head[u] ; head[u] = cnt++ ;
p[cnt].v = u ; p[cnt].w = 0 ; p[cnt].s = -s ;
p[cnt].next = head[v] ; head[v] = cnt++ ;
}
int spfa(int s,int t)
{
int u , v , i ;
memset(pre,-1,sizeof(pre));
memset(dis,INF,sizeof(dis));
memset(vis,0,sizeof(vis));
while( !q.empty() )
q.pop();
q.push(s) ;
vis[s] = 1 ;
dis[s] = 0 ;
while( !q.empty() )
{
u = q.front();
q.pop();
vis[u] = 0 ;
for(i = head[u] ; i != -1 ; i = p[i].next)
{
v = p[i].v ;
if( p[i].w && dis[v] > dis[u] + p[i].s )
{
dis[v] = dis[u] + p[i].s ;
pre[v] = i ;
if( !vis[v] )
{
vis[v] = 1 ;
q.push(v) ;
}
}
}
}
if( pre[t] == -1 )
return 0 ;
return 1 ;
}
void f(int s,int t)
{
int i , min1 , ans = 0 ;
while( spfa(s,t) )
{
min1 = INF ;
for(i = pre[t] ; i != -1 ; i = pre[ p[i^1].v ])
if( p[i].w < min1 )
min1 = p[i].w ;
for(i = pre[t] ; i != -1 ; i = pre[ p[i^1].v ])
{
p[i].w -= min1 ;
p[i^1].w += min1 ;
ans += p[i].s*min1 ;
}
}
printf("%d\n", ans);
}
int main()
{
int n , nh , nm , m , i , j ;
while(scanf("%d %d", &n, &m)!=EOF)
{
/*建图方式,源点连接到人(容量是1,花费是0),人连接到所有的房屋(容量是1,花费是人与房屋的距离),房屋连接到汇点(容量是1,花费是0),其他的就是模板了*/
cnt = 0 ;
nh = 1 ;
nm = 1 ;
memset(head,-1,sizeof(head));
if(n == 0 && m == 0)
break;
for(i = 0 ; i < n ; i++)
scanf("%s", str[i]);
for(i = 0 ; i < n ; i++)
for(j = 0 ; j < m ; j++)
if( str[i][j] == 'm' )
{
mm[nm].x = i ;
mm[nm++].y = j ;
}
else if( str[i][j] == 'H' )
{
hh[nh].x = i ;
hh[nh++].y = j ;
}
for(i = 1 ; i < nm ; i++)
add(0,i,1,0);
for(i = 1 ; i < nm ; i++)
for(j = 1 ; j < nh ; j++)
{
add(i,j+100,1, fabs(mm[i].x-hh[j].x)+fabs(mm[i].y-hh[j].y) );//由人和房屋的坐标计算人到房屋的花费
}
for(i = 1 ; i < nh ; i++)
add(i+100,201,1,0);//最多人或房屋均为100,设人的标号为1到100,房屋的标号101到200,源点0,汇点201
f(0,201);
}
return 0;
}
poj2195--Going Home(最小费用最大流),布布扣,bubuko.com
标签:des http os io strong for ar art
原文地址:http://blog.csdn.net/winddreams/article/details/38711627