版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/91352783
title
LUOGU 4014
题目描述
有 n 件工作要分配给 n 个人做。第 i 个人做第 j 件工作产生的效益为 。试设计一个将 n 件工作分配给 n 个人做的分配方案,使产生的总效益最大。
输入输出格式
输入格式:
文件的第 1 行有 1 个正整数 n,表示有 n 件工作要分配给 n 个人做。
接下来的 n 行中,每行有 n 个整数 ,表示第 i 个人做第 j 件工作产生的效益为 。
输出格式:
两行分别输出最小总效益和最大总效益。
输入输出样例
输入样例#1:
5
2 2 2 1 2
2 3 1 2 4
2 0 1 1 1
2 3 4 3 3
3 2 1 2 1
输出样例#1:
5
14
说明
扫描二维码关注公众号,回复:
6394844 查看本文章
一个人只能修一个工件
analysis
写了这么久网络流24题,头一次碰上模型完全一样的两道题,分配问题和运输问题真算是一对奇葩。
建图完全一样:
- 1. 向 连接容量为 ,费用为 的边。
- 2. 向 连接容量为 ,费用为 。
- 3. 向 连接容量为 ,费用为 的边。
跑一个最小费用最大流,轻松完成第一个任务。
第二个任务只要清空图,然后重新连接为费用是
的边即可。
至于为啥他们的容量都为 ?那是因为一个人只能修一件工件,一件工件只能被一个人修,即都只能被使用一次。
这一次是真的轻松了吧。
code
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10,maxm=210,inf=0x3f3f3f3f;
char buf[1<<15],*fs,*ft;
inline char getc() { return (ft==fs&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),ft==fs))?0:*fs++; }
template<typename T>inline void read(T &x)
{
x=0;
T f=1, ch=getchar();
while (!isdigit(ch) && ch^'-') ch=getchar();
if (ch=='-') f=-1, ch=getchar();
while (isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48), ch=getchar();
x*=f;
}
template<typename T>inline void write(T x)
{
if (!x) { putchar('0'); return ; }
if (x<0) putchar('-'), x=-x;
T num=0, ch[20];
while (x) ch[++num]=x%10+48, x/=10;
while (num) putchar(ch[num--]);
}
int ver[maxn<<1],edge[maxn<<1],Next[maxn<<1],cost[maxn<<1],head[maxn],len=1;
inline void add(int x,int y,int z,int c)
{
ver[++len]=y,edge[len]=z,cost[len]=c,Next[len]=head[x],head[x]=len;
ver[++len]=x,edge[len]=0,cost[len]=-c,Next[len]=head[y],head[y]=len;
}
int s,t;
int dist[maxn],incf[maxn],pre[maxn];
bool vis[maxn];
inline bool spfa()
{
memset(dist,0x3f,sizeof(dist));
memset(vis,0,sizeof(vis));
queue<int>q;q.push(s);
dist[s]=0,vis[s]=1,incf[s]=1<<30;
while (!q.empty())
{
int x=q.front();
q.pop();
vis[x]=0;
for (int i=head[x]; i; i=Next[i])
{
if (!edge[i]) continue;
int y=ver[i];
if (dist[y]>dist[x]+cost[i])
{
dist[y]=dist[x]+cost[i];
incf[y]=min(incf[x],edge[i]);
pre[y]=i;
if (!vis[y]) q.push(y),vis[y]=1;
}
}
}
if (dist[t]==inf) return false;
else return true;
}
long long maxflow,ans;
inline void update()
{
int x=t;
while (x!=s)
{
int i=pre[x];
edge[i]-=incf[t];
edge[i^1]+=incf[t];
x=ver[i^1];
}
maxflow+=incf[t];
ans+=dist[t]*incf[t];
}
int n,c[maxm][maxm];
inline void build(int off)
{
memset(head,0,sizeof(head));
len=1;
ans=maxflow=0;
s=0,t=n<<1|1;
for (int i=1; i<=n; ++i) add(s,i,1,0);
for (int i=1; i<=n; ++i)
for (int j=1; j<=n; ++j) add(i,j+n,1,c[i][j]*off);
for (int i=1; i<=n; ++i) add(i+n,t,1,0);
}
int main()
{
read(n);
for (int i=1; i<=n; ++i)
for (int j=1; j<=n; ++j) read(c[i][j]);
build(1);
while (spfa()) update();
write(ans),puts("");
build(-1);
while (spfa()) update();
write(-ans),puts("");
return 0;
}