【网络流24题】分配问题(费用流)
题面
题解
这。。。。二分图最大带权匹配呀
KM可以直接AC
懒得写了
一个费用流跑过去了
和运输问题一毛一样呀。。。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 5000
#define MAXL 500000
#define INF 1000000000
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
struct Line
{
int v,next,w,fy;
}e[MAXL];
bool vis[MAX];
int h[MAX],cnt=2;
int a[MAX],b[MAX],c[MAX][MAX];
inline void Add(int u,int v,int w,int fy)
{
e[cnt]=(Line){v,h[u],w,fy};h[u]=cnt++;
e[cnt]=(Line){u,h[v],0,-fy};h[v]=cnt++;
}
int pe[MAX],pr[MAX],dis[MAX];
int S,T,Cost,n,m,Flow,opt=1;
bool SPFA()
{
memset(dis,63,sizeof(dis));
queue<int> Q;
Q.push(S);dis[S]=0;
while(!Q.empty())
{
int u=Q.front();Q.pop();
for(int i=h[u];i;i=e[i].next)
{
int v=e[i].v;
if(e[i].w&&dis[v]>dis[u]+e[i].fy)
{
dis[v]=dis[u]+e[i].fy;
pe[v]=i;pr[v]=u;
if(!vis[v])vis[v]=true,Q.push(v);
}
}
vis[u]=false;
}
if(dis[T]>=INF)return false;
int flow=INF;
for(int i=T;i!=S;i=pr[i])flow=min(flow,e[pe[i]].w);
for(int i=T;i!=S;i=pr[i])e[pe[i]].w-=flow,e[pe[i]^1].w+=flow;
Cost+=opt*flow*dis[T];
Flow+=flow;
return true;
}
int main()
{
freopen("job.in","r",stdin);
freopen("job.out","w",stdout);
n=read();
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
c[i][j]=read();
S=0;T=n+n+1;
memset(h,0,sizeof(h));cnt=2;
for(int i=1;i<=n;++i)Add(S,i,1,0);
for(int j=1;j<=n;++j)Add(j+n,T,1,0);
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
Add(i,j+n,1,c[i][j]);
Cost=Flow=0;opt=1;
while(SPFA());
printf("%d\n",Cost);
memset(h,0,sizeof(h));cnt=2;
for(int i=1;i<=n;++i)Add(S,i,1,0);
for(int j=1;j<=n;++j)Add(j+n,T,1,0);
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
Add(i,j+n,INF,-c[i][j]);
Cost=Flow=0;opt=-1;
while(SPFA());
printf("%d\n",Cost);
return 0;
}