P8215 [THUPC2022 初赛] 分组作业
Description
有
有
求最小不满总和。
Solution
这题可以说是大多是网络流建模套路的综合。考虑最小割模型。做之前建议先做小 M 的作物。
为表示愿意或不愿意这种二选一的关系,使用“串联电路”。从源点向代表第
第
现在的问题就是设计一种“开关”,表示是否合作。因为只有两人都愿意才能选择合作或不合作,否则只能不合作。所以对于第
注意,要再虚拟一点,夹在表示是否合作的点与汇点的连边上,后面有关合作的边都与此点相连,为的是防止有关合作的边影响到代表队员的点,导致求出错误答案。
对于一个喜欢关系,
最后求出的最小割,减去 long long。
C++ Code
#include <bits/stdc++.h>
using namespace std;
class Dinic {
public:
typedef long long TYPE;
static const int maxn = 5000 * 5, inf = 0x7f7f7f7f, maxm = inf;
class edge {
public:
int to, rev;
TYPE flow;
edge(int to, TYPE flow, int rev): to(to), flow(flow), rev(rev) {}
edge() {}
};
std::vector<edge>vec[maxn];
int h[maxn], cur[maxn], n, m, s, t;
Dinic(int n, int m, int s, int t): n(n), m(m), s(s), t(t),
h({0}), cur({0}) {}
Dinic() {}
inline bool bfs() {
std::memset(h, inf, sizeof(h));
h[t] = 0;
std::memset(cur, 0, sizeof(cur));
int q[maxn], front = 0, back = -1;
std::memset(q, 0, sizeof(q));
for (q[++back] = t; front <= back;) {
int u = q[front++];
for (edge &e : vec[u]) {
int v = (e.to);
if (vec[v][e.rev].flow && h[v] == inf) {
h[v] = h[u] + 1;
q[++back] = v;
}
}
}
return h[s] != inf;
}
inline TYPE dfs(int u, TYPE flow) {
if (u == t || !flow) {
return flow;
}
TYPE res = 0;
int sz = vec[u].size();
for (int &i = cur[u]; i < sz && flow; ++i) {
edge &e = vec[u][i];
int v = e.to;
if (e.flow && h[v] + 1 == h[u]) {
TYPE Preflow = dfs(v, std::min(e.flow, flow));
flow -= Preflow, res += Preflow;
e.flow -= Preflow, vec[v][e.rev].flow += Preflow;
}
}
return res;
}
inline TYPE GetMaxFlow() {
TYPE res = 0;
while (bfs()) {
TYPE Preflow = 0;
while ((Preflow = dfs(s, inf))) {
res += Preflow;
}
}
return res;
}
inline void Add_Edge(int from, int to, TYPE flow) {
vec[from].push_back(edge(to, flow, vec[to].size()));
vec[to].push_back(edge(from, 0, vec[from].size() - 1));
}
inline void Solve() {
#define id(a,CLASS) (a+(CLASS)*(N))
#define Which(a) ((a-1)/2+1)
int N, M;
scanf("%d%d", &N, &M);
this[0] = Dinic((N << 2) + 2, inf, 0, (N << 2) + 1);
for (int i = 1; i <= (N << 1); ++i) {
int c, d, e;
scanf("%d%d%d", &c, &d, &e);
Add_Edge(id(Which(i), !(i & 1)), t, c);
Add_Edge(s, id(Which(i), !(i & 1)), d);
Add_Edge(id(Which(i), !(i & 1)), id(Which(i), (i & 1)), e);
}
for (int i = 1; i <= N; ++i) {
Add_Edge(s, id(i, 2), inf);
Add_Edge(id(i, 3), t, inf);
Add_Edge(id(i, 2), id(i, 3), inf);
Add_Edge(id(i, 2), id(i, 0), inf);
Add_Edge(id(i, 2), id(i, 1), inf);
}
for (int i = 1; i <= M; ++i) {
int A, B, a, b;
scanf("%d%d%d%d", &A, &B, &a, &b);
Add_Edge(id(Which(B), !(B & 1)), id(Which(A), 3), a);
Add_Edge(id(Which(B), 3), id(Which(A), !(A & 1)), b);
}
printf("%lld\n", GetMaxFlow() - (long long)inf * N);
}
};
Dinic Main;
int main() {
Main.Solve();
return 0;
}