Description
Solution
费用流裸题。
至于最大效益,取相反数即可。
Code
/************************************************
* Au: Hany01
* Date: Jul 12th, 2018
* Prob: LOJ6012
* Email: hany01@foxmail.com
* Inst: Yali High School
************************************************/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define x first
#define y second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia
template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }
inline int read() {
static int _, __; static char c_;
for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
return _ * __;
}
const int maxn = 205, maxm = 205 * 205;
int n, S, T, beg[maxn], v[maxm], nex[maxm], f[maxm], w[maxm], dis[maxn], vis[maxn], e = 1, cost, a[105][105];
inline void add(int uu, int vv, int ff, int ww, int fl = 1) {
v[++ e] = vv, f[e] = ff, w[e] = ww, nex[e] = beg[uu], beg[uu] = e;
if (fl) add(vv, uu, 0, -ww, 0);
}
inline bool BFS()
{
static queue<int> q;
For(i, 1, T) dis[i] = INF;
Set(vis, 0), dis[S] = 0, q.push(S);
while (!q.empty()) {
int u = q.front(); q.pop(), vis[u] = 0;
for (register int i = beg[u]; i; i = nex[i])
if (f[i] && chkmin(dis[v[i]], dis[u] + w[i]))
if (!vis[v[i]]) vis[v[i]] = 1, q.push(v[i]);
}
return dis[T] != INF;
}
int DFS(int u, int flow)
{
if (u == T) return flow;
int t, res = flow;
vis[u] = 1;
for (register int i = beg[u]; i; i = nex[i])
if (f[i] && dis[v[i]] == dis[u] + w[i] && !vis[v[i]]) {
t = DFS(v[i], min(flow, f[i])), f[i] -= t, f[i ^ 1] += t, cost += w[i] * t;
if (!(res -= t)) return flow;
}
return flow - res;
}
int main()
{
#ifdef hany01
File("loj6012");
#endif
T = (S = ((n = read()) << 1) + 1) + 1;
For(i, 1, n) {
For(j, 1, n) add(i, j + n, 1, a[i][j] = read());
add(S, i, 1, 0), add(i + n, T, 1, 0);
}
while (BFS()) do Set(vis, 0), DFS(S, INF); while (vis[T]);
printf("%d\n", cost);
cost = 0, Set(beg, 0), e = 1;
For(i, 1, n) {
For(j, 1, n) add(i, j + n, 1, -a[i][j]);
add(S, i, 1, 0), add(i + n, T, 1, 0);
}
while (BFS()) do Set(vis, 0), DFS(S, INF); while (vis[T]);
printf("%d\n", -cost);
return 0;
}
//爱子心无尽,归家喜及辰。
// -- 蒋士铨《岁暮到家》