简单的费用流问题,每个人对每个任务连边,每个任务对汇点连,源点对每个人连,最大费用取反即可

#include<bits/stdc++.h>
using namespace std;
#define lowbit(x) ((x)&(-x))
typedef long long LL;
const int maxm = 2e4+5;
const int INF = 0x3f3f3f3f;
struct edge{
int u, v, cap, flow, cost, nex;
} edges[maxm];
int head[maxm], cur[maxm], cnt, fa[333], d[333], n, val[105][105];
bool inq[333];
void init() {
memset(head, -1, sizeof(head));
}
void add(int u, int v, int cap, int cost) {
edges[cnt] = edge{u, v, cap, 0, cost, head[u]};
head[u] = cnt++;
}
void addedge(int u, int v, int cap, int cost) {
add(u, v, cap, cost), add(v, u, 0, -cost);
}
bool spfa(int s, int t, int &flow, LL &cost) {
for(int i = 0; i <= 2*n+3; ++i) d[i] = INF; //init()
memset(inq, false, sizeof(inq));
d[s] = 0, inq[s] = true;
fa[s] = -1, cur[s] = INF;
queue<int> q;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for(int i = head[u]; i != -1; i = edges[i].nex) {
edge& now = edges[i];
int v = now.v;
if(now.cap > now.flow && d[v] > d[u] + now.cost) {
d[v] = d[u] + now.cost;
fa[v] = i;
cur[v] = min(cur[u], now.cap - now.flow);
if(!inq[v]) {q.push(v); inq[v] = true;}
}
}
}
if(d[t] == INF) return false;
flow += cur[t];
cost += 1LL*d[t]*cur[t];
for(int u = t; u != s; u = edges[fa[u]].u) {
edges[fa[u]].flow += cur[t];
edges[fa[u]^1].flow -= cur[t];
}
return true;
}
int MincostMaxflow(int s, int t, LL &cost) {
cost = 0;
int flow = 0;
while(spfa(s, t, flow, cost));
return flow;
}
void build_graph(int f) {
init();
int s = 0, t = 2*n+1;
for(int i = 1; i <= n; ++i) {
addedge(s, i, 1, 0);
for(int j = 1; j <= n; ++j) {
addedge(i, j+n, 1, f*val[i][j]);
}
}
for(int i = 1; i <= n; ++i)
addedge(i+n, t, 1, 0);
}
void run_case() {
cin >> n;
int s = 0, t = 2*n+1;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
cin >> val[i][j];
build_graph(1);
LL cost = 0;
MincostMaxflow(s, t, cost);
cout << cost << "\n";
build_graph(-1);
cost = 0;
MincostMaxflow(s, t, cost);
cout << -cost;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
run_case();
cout.flush();
return 0;
}
来源:https://www.cnblogs.com/GRedComeT/p/12298607.html
