HDU 1533 最小费用最大流(模板)

http://acm.hdu.edu.cn/showproblem.php?pid=1533

这道题直接用了模板

题意:要构建一个二分图,家对应人,连线的权值就是最短距离,求最小费用

要注意void init(int n) 这个函数一定要写

一开始忘记写这个WA了好几发

还有这个题很容易T掉,赋值建图要简化,一开始构建成网络流那种图一直T

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define oo 0x13131313
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN=;
const int MAXM=;
struct Edge
{
int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;
void init(int n)
{
N = n;
tol = ;
memset(head,-,sizeof(head));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = ;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = ;
edge[tol].cost = -cost;
edge[tol].flow = ;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int>q;
for(int i = ; i < N; i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -;
}
dis[s] = ;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -; i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] +edge[i].cost)
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -)return false;
else return true;
}
int minCostMaxflow(int s,int t,int &cost)
{
int flow = ;
cost = ;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t]; i != - ; i = pre[edge[i^].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -; i = pre[edge[i^].to])
{
edge[i].flow += Min;
edge[i^].flow -= Min;
cost += edge[i].cost*Min;
}
flow += Min;
}
return flow;
}
struct Home
{
int x,y;
} H[MAXN],P[MAXN];
int main()
{
int totH,totP;
int NN,MM;
while(cin>>NN>>MM&&NN&&MM)
{
getchar();
init(MAXN);
char c;
totH=;
totP=;
for(int i=; i<=NN; i++)
{
for(int j=; j<=MM; j++)
{
scanf("%c",&c);
if(c=='H') totH++,H[totH].x=i,H[totH].y=j;
else if(c=='m') totP++,P[totP].x=i,P[totP].y=j;
}
getchar();
} int ANS=;
int NNN=totP+totH;
for(int i=; i<=totP; i++)
for(int j=; j<=totH; j++)
{
int t=abs(P[i].x-H[j].x)+abs(P[i].y-H[j].y);
addedge(i,j+totP,,t);
}
for(int i=; i<=totP; i++)
addedge(NNN+,i,,);
for(int i=totP+; i<=NNN; i++)
addedge(i,NNN+,,);
minCostMaxflow(NNN+,NNN+,ANS);
printf("%d\n",ANS);
}
return ;
}
上一篇:java 学习第三篇if判断


下一篇:从.Net到Java学习第五篇——Spring Boot &&Profile &&Swagger2