[TJOI 2015] 线性代数

题目大意

给定 n×nn \times n 的矩阵 B\mathbf{B}1×n1 \times n 的矩阵 C\mathbf{C},另有一个未知的 1×n1 \times n 的 01 矩阵A\mathbf{A}。定义:

D=(ABC)×ATD = (\mathbf{A} \mathbf{B} - \mathbf{C}) \times \mathbf{A}^T

DD 的最大值。

1n5001 \leqslant n \leqslant 500

0bi,j,  ci1,0000 \leqslant b_{i,j}, \; c_i \leqslant 1,000

题目链接

【TJOI 2015】线性代数 - LibreOJ 2100

题解

化一下式子,显然有:

D=i=1nj=1nbi,jaiaji=1naiciD = \sum_{i = 1}^{n} \sum_{j = 1}^{n} b_{i, j} a_i a_j - \sum_{i = 1}^{n} a_i c_i

由于 A\mathbf{A} 是 01 矩阵,我们可以这么转化一下问题:有 nn 个物品,代价为 cic_i,同时选择两个的获益为 bi,jb_{i, j},求最大获益。这是显然的最大权闭合图。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <cstdio>
#include <climits>
#include <queue>
#include <algorithm>
const int MAXN = 505;
struct Edge;
struct Node {
Edge *e, *curr;
int level;
} N[MAXN * MAXN];
struct Edge {
Node *u, *v;
Edge *next, *rev;
int cap, flow;
Edge(Node *u, Node *v, int cap) : u(u), v(v), cap(cap), flow(0), next(u->e) {}
};
void addEdge(int u, int v, int cap) {
N[u].e = new Edge(&N[u], &N[v], cap);
N[v].e = new Edge(&N[v], &N[u], 0);
N[u].e->rev = N[v].e;
N[v].e->rev = N[u].e;
}
namespace Dinic {
bool makeLevelGraph(Node *s, Node *t, int n) {
for (int i = 0; i < n; i++) N[i].level = 0;
std::queue<Node *> q;
q.push(s);
s->level = 1;
while (!q.empty()) {
Node *u = q.front();
q.pop();
for (Edge *e = u->e; e; e = e->next) {
if (e->cap > e->flow && e->v->level == 0) {
e->v->level = u->level + 1;
if (e->v == t) return true;
q.push(e->v);
}
}
}
return false;
}
int findPath(Node *s, Node *t, int limit = INT_MAX) {
if (s == t) return limit;
for (Edge *&e = s->curr; e; e = e->next) {
if (e->cap > e->flow && e->v->level == s->level + 1) {
int flow = findPath(e->v, t, std::min(limit, e->cap - e->flow));
if (flow > 0) {
e->flow += flow;
e->rev->flow -= flow;
return flow;
}
}
}
return 0;
}
int solve(int s, int t, int n) {
int res = 0;
while (makeLevelGraph(&N[s], &N[t], n)) {
for (int i = 0; i < n; i++) N[i].curr = N[i].e;
int flow;
while ((flow = findPath(&N[s], &N[t])) > 0) res += flow;
}
return res;
}
}
int n;
int getID(int x, int y) {
return x * n + y;
}
int main() {
scanf("%d", &n);
const int s = 0, t = n + n * n + 1;
int tot = 0;
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) {
int x;
scanf("%d", &x);
addEdge(getID(i, j), i, INT_MAX);
addEdge(getID(i, j), j, INT_MAX);
addEdge(s, getID(i, j), x);
tot += x;
}
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
addEdge(i, t, x);
}
printf("%d\n", tot - Dinic::solve(s, t, t + 1));
return 0;
}