我的:
int tail[kMaxN * 20], pre[kMaxM], to[kMaxM], val[kMaxM], dep[kMaxN * 20], cur[kMaxN * 20];
bool vis[kMaxN * 20];
void add(int u, int v, int w) {
to[++tot] = v, pre[tot] = tail[u], val[tot] = w, tail[u] = tot;
}
void adde(int u, int v, int w) {
add(u, v, w), add(v, u, 0);
}
bool bfs() {
std::queue<int> q;
for (int i = 1; i <= cnt; ++i) {
dep[i] = kInf, cur[i] = tail[i], vis[i] = 0;
}
q.emplace(s), dep[s] = 0, vis[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = tail[u]; i; i = pre[i]) {
int v = to[i], w = val[i];
if (!w || vis[v]) continue;
vis[v] = 1, dep[v] = dep[u] + 1, q.emplace(v);
}
}
return vis[t];
}
int dfs(int u, int flow) {
if (u == t || !flow) return flow;
int ret = 0;
for (int &i = cur[u]; i && flow; i = pre[i]) {
int v = to[i], w = val[i];
if (dep[v] == dep[u] + 1 && w) {
int tmp = dfs(v, std::min(w, flow));
if (!tmp) dep[v] = 0;
flow -= tmp, ret += tmp;
val[i] -= tmp, val[i ^ 1] += tmp;
}
}
return ret;
}
那个人的:
struct Graph {
struct Node {
int v, w, nxt;
};
std::vector<int> head;
std::vector<Node> edge;
Graph() {
}
Graph(int n) : head(n + 1, -1){};
void resize(int n) {
head.assign(n + 1, -1);
}
void add(int u, int v, int w) {
if (head.size() < u) {
head.reserve(u * 2);
}
edge.emplace_back(Node{v, w, head[u]});
head[u] = edge.size() - 1;
}
void add_flow(int u, int v, int w) {
add(u, v, w);
add(v, u, 0);
}
};
namespace NetworkFlow {
std::vector<int> level;
bool bfs(int S, int T, const Graph &G) {
level.assign(G.head.size(), 0);
level[S] = 1;
std::queue<int> q;
q.push(S);
while (!q.empty()) {
int now = q.front();
q.pop();
for (int i = G.head[now]; ~i; i = G.edge[i].nxt) {
int v = G.edge[i].v;
if (!level[v] && G.edge[i].w) {
level[v] = level[now] + 1;
q.push(v);
}
}
}
return level[T];
}
std::vector<int> cur;
int dfs(int x, int T, int maxflow, Graph &G) {
if (x == T) {
return maxflow;
}
int res = 0;
for (int i = cur[x]; ~i && res < maxflow; i = G.edge[i].nxt) {
cur[x] = i;
int v = G.edge[i].v;
if (G.edge[i].w && level[v] == level[x] + 1) {
int x = dfs(v, T, std::min(G.edge[i].w, maxflow - res), G);
if (x) {
G.edge[i].w -= x;
G.edge[i ^ 1].w += x;
res += x;
}
}
}
if (res < maxflow) {
level[x] = -1;
}
return res;
}
int MaxFlow(const int S, const int T, const Graph &G) {
cur.resize(G.head.size());
level.resize(G.head.size());
Graph tmpG = G;
int res = 0;
while (bfs(S, T, tmpG)) {
cur.assign(tmpG.head.begin(), tmpG.head.end());
int x;
while (x = dfs(S, T, INF, tmpG)) {
res += x;
}
}
return res;
}
} // namespace NetworkFlow
都是在 CF793G 里面的一个点数为 311661 边数为 1199499 的图里面跑,他的只要150ms,我的到了6500ms的时限了还没跑完!
这是为什么啊啊啊