Nemaleswang的博客通过本文主要向大家介绍了hdoj,hdoj题目分类,杭电hdoj,hdoj1003,hdoj1002等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
题目大意:现在有一张图,有n个房间和n个人,现在每个人移动的代价是1,只能上下左右移动,不能有相同的人在一个房间,问所有的人都进入房间的最小花费是多少
题目思路:这种有限制而且还有花费的,我们不妨转化为最小费用最大流,我们用一个超级源点连接所有的人,容量为1,单位花费为0,然后用一个超级汇点被所有的房间连接,容量为1,单位花费为0,然后每个人和所有房间相连,容量为1,单位花费为这个人和这个房间的距离,然后直接跑最小费用最大流就好了
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MaxNode = 205;
const int MaxEdge = 40005;
struct Edge{
int to,vol,cost,next;
}Edges[MaxEdge];
int Pre[MaxNode],Path[MaxNode],Dist[MaxNode],Head[MaxNode],EdgeCount;
void addedge(int u, int v, int vol, int cost){
Edges[EdgeCount].to = v;
Edges[EdgeCount].vol = vol;
Edges[EdgeCount].cost = cost;
Edges[EdgeCount].next = Head[u];
Head[u] = EdgeCount++;
Edges[EdgeCount].to = u;
Edges[EdgeCount].vol = 0;
Edges[EdgeCount].cost = -cost;
Edges[EdgeCount].next = Head[v];
Head[v] = EdgeCount++;
}
bool Spfa(int s, int t){
memset(Dist, 0x3f3f3f3f, sizeof(Dist));
memset(Pre, -1, sizeof(Pre));
Dist[s] = 0;
queue<int>Q;
Q.push(s);
while (!Q.empty()){
int u = Q.front();
Q.pop();
for (int e = Head[u]; e != -1; e = Edges[e].next){
int v = Edges[e].to;
if (Edges[e].vol > 0 && Dist[v] > Dist[u] + Edges[e].cost){
Dist[v] = Dist[u] + Edges[e].cost;
Pre[v] = u;
Path[v] = e;
Q.push(v);
}
}
}
return Pre[t] != -1;
}
int MinCostFlow(int s, int t){
int cost = 0;
int max_flow = 0;
int u, v, e;
while (Spfa(s, t)){
int f = INF;
for (u = t; u != s; u = Pre[u]){
f = min(f, Edges[Path[u]].vol);
}
for (u = t; u != s; u = Pre[u]){
e = Path[u];
Edges[e].vol -= f;
Edges[e^1].vol += f;
}
max_flow += f;
cost += f*Dist[t];
}
return cost;
}
void init(){
memset(Head,-1,sizeof(Head));
EdgeCount = 0;
}
char gMap[MaxNode][MaxNode];
vector<pair<int, int> > gHousVec;
vector<pair<int, int> > gManVec;
int main(){
int n,m;
char mp[MaxNode][MaxNode];
while(~scanf("%d%d",&n,&m)&&n+m){
init();
gHousVec.clear();
gManVec.clear();
for(int i = 1;i <= n;i++){
getchar();
for(int j = 1;j <= m;j++){
scanf("%c",&mp[i][j]);
if(mp[i][j] == 'm') gManVec.push_back(pair<int,int>(i,j));
else if(mp[i][j] == 'H') gHousVec.push_back(pair<int,int>(i,j));
}
}
int u = gHousVec.size();
for (int i = 1; i <= u; i++) addedge(0, i, 1, 0);
for (int i = 0; i < u; i++){
for (int j = 0; j < u; j++){
int value = abs(gManVec[i].first - gHousVec[j].first) + abs(gManVec[i].second - gHousVec[j].second);
addedge(i + 1, j + u + 1, 1, value);
}
}
for (int i = 1; i <= u; i++) addedge(u + i, 2 * u + 1, 1, 0);
int cost = MinCostFlow(0,2*u+1);
printf("%d\n",cost);
}
return 0;
}