这题,,没什么好说的,,裸的费用流
#include<iostream>
#include<map>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<set>
#include<string.h>
#include<string>
#include<vector>
#define MX 1111
#define INF 0x3f3f3f3f
#define mem(x,y) memset(x,y,sizeof(x))
#define FIN freopen("input.txt","r",stdin)
using namespace std;
int n,m;
int head[MX],rear;
struct Edge
{
int nxt,to,cap,cost;
} edge[MX*111];
void edge_init()
{
mem(head,-1);
rear=0;
}
void edge_add(int a,int b,int cap,int cost)
{
edge[rear].cost=cost;
edge[rear].cap=cap;
edge[rear].nxt=head[a];
edge[rear].to=b;
head[a]=rear++;
}
int dis[MX],pre[MX]; //储存前驱顶点
bool vis[MX];
bool spfa(int s, int t)
{
mem(dis,0x3f);
mem(vis,0);
mem(pre,-1);
deque<int>q;
q.push_back(s);
dis[s]=0,vis[s]=1;
while (!q.empty())
{
int u = q.front();
q.pop_front();
vis[u] = 0;
for (int i= head[u]; ~i; i=edge[i].nxt)
{
int v=edge[i].to;
if (edge[i].cap&& dis[v]>dis[u]+edge[i].cost)
{
dis[v]=dis[u]+edge[i].cost;
pre[v] = i;
if (!vis[v])
{
vis[v]=1;
if(!q.empty()&&dis[v]<=dis[q.front()])q.push_front(v);//SLF优化
else q.push_back(v);
}
}
}
}
if (pre[t]==-1) return 0;
else return 1;
}
//返回的是最大流, cost存的是最小费用
int MCMF(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while (spfa(s, t))
{
int Min = INF;
for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to])
if (Min > edge[i].cap) Min = edge[i].cap;
for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to])
edge[i].cap -= Min,edge[i ^ 1].cap += Min;
cost += dis[t]* Min;
flow+=Min;
}
return flow;
}
int main()
{
FIN;
while(~scanf("%d%d",&n,&m))
{
int s=0,t=n+m+1;
edge_init();
for(int i=1; i<=n; i++)
{
int x;
scanf("%d",&x);
edge_add(s,i,x,0);
edge_add(i,s,0,0);
}
for(int i=1; i<=m; i++)
{
int x;
scanf("%d",&x);
edge_add(n+i,t,x,0);
edge_add(t,n+i,0,0);
}
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
{
int x;
scanf("%d",&x);
edge_add(i,n+j,INF,x);
edge_add(n+j,i,0,-x);
}
int cost=0;
MCMF(s,t,cost);
printf("%d\n",cost);
for(int i=s; i<=t; i++) for(int j=head[i]; ~j; j=edge[j].nxt)if(i<edge[j].to)
{
edge[j].cap+=edge[j^1].cap;
edge[j^1].cap=0;
edge[j].cost=-edge[j].cost;
edge[j^1].cost=-edge[j^1].cost;
}
cost=0;
MCMF(s,t,cost);
printf("%d\n",-cost);
}
return 0;
}