3 5 5 0 1 5 0 2 7 1 1 6 1 2 3 2 4 5 1 1 1 0 0 0 1 1 0
Case 1: 18 Case 2: 0 Case 3: -1
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
#define MAXN 5555
#define MAXM 501000
#define INF 0x3f3f3f3f
int pre[MAXN],vis[MAXN],head[MAXN],n,m,e,dis[MAXN],cnt;
int source,sink;
struct node
{
int u,v,cap,flow,cost,next;
}edge[MAXM];
void init()
{
memset(head,-1,sizeof(head));
cnt=0;
}
void add(int a,int b,int c,int d)
{
node E={a,b,c,0,d,head[a]};
edge[cnt]=E;
head[a]=cnt++;
node E1={b,a,0,0,-d,head[b]};
edge[cnt]=E1;
head[b]=cnt++;
}
bool BFS(int s,int t)
{
memset(vis,0,sizeof(vis));
memset(dis,-INF,sizeof(dis));
memset(pre,-1,sizeof(pre));
vis[s]=1;
dis[s]=0;
queue<int>q;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
node E=edge[i];
if(dis[E.v]<dis[u]+E.cost&&E.cap>E.flow)
{
dis[E.v]=dis[u]+E.cost;
pre[E.v]=i;
if(!vis[E.v])
{
q.push(E.v);
vis[E.v]=1;
}
}
}
}
return pre[t]!=-1;
}
void mcmf(int s,int t,int &cost,int &flow)
{
flow=cost=0;
while(BFS(s,t))
{
int Min=INF;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].v])
{
node E=edge[i];
Min=min(Min,E.cap-E.flow);
}
for(int i=pre[t];i!=-1;i=pre[edge[i^1].v])
{
edge[i].flow+=Min;
edge[i^1].flow-=Min;
cost+=edge[i].cost*Min;
}
flow+=Min;
}
}
void getmap()
{
int a,b,c;
for(int i=0;i<e;i++)
{
scanf("%d%d%d",&a,&b,&c);
if(c>=0)
add(a+1,b+1+n,1,c);
}
for(int i=1;i<=n;i++)
add(source,i,1,0);
for(int i=1;i<=m;i++)
add(i+n,sink,1,0);
}
int main()
{
int k=1;
while(scanf("%d%d%d",&n,&m,&e)!=EOF)
{
init();
source=0,sink=n+m+1;
getmap();
int cost,flow;
mcmf(source,sink,cost,flow);
printf("Case %d: ",k++);
if(flow==n)
printf("%d\n",cost);
else
printf("-1\n");
}
return 0;
}hdoj--2426--Interesting Housing Problem(最大费用流)
原文:http://blog.csdn.net/qq_29963431/article/details/51364687