POJ: Dual Core CPU

3 1
1 10
2 10
10 3
2 3 1000
13
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;struct SEdge {
int to;
int cap;
int rev;
SEdge(int t, int c, int r): to(t), cap(c), rev(r) {}
};
#define MAX_N 20000
#define MAX_M 200000
#define INF 0x3f3f3f3f
vector<SEdge> G[MAX_N + 2];
int level[MAX_N + 2];
int iter[MAX_N + 2];
void add_edge(int from, int to, int cap) {
SEdge fromEdge(to, cap, (int)G[to].size());
G[from].push_back(fromEdge);
SEdge toEdge(from, 0, (int)G[from].size() - 1);
G[to].push_back(toEdge);
}
void bfs(int s) {
memset(level, -1, sizeof(level));
queue<int> q;
level[s] = 0;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (int i = 0; i < G[v].size(); ++i) {
SEdge &e = G[v][i];
if (e.cap > 0 && level[e.to] < 0) {
level[e.to] = level[v] + 1;
q.push(e.to);
}
}
}
}
int dfs(int v, int t, int f) {
if (v == t) return f;
for (int &i = iter[v]; i < G[v].size(); ++i) {
SEdge &e = G[v][i];
if (e.cap > 0 && level[v] < level[e.to]) {
int d = dfs(e.to, t, min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
while (true) {
bfs(s);
if (level[t] < 0) return flow;
memset(iter, 0, sizeof(iter));
int f;
while ((f = dfs(s, t, INF)) > 0) flow += f;
}
}
int main(int argc, char *argv[]) {
int n, m;
scanf("%d%d", &n, &m);
int s = n;
int t = s + 1;
for (int i = 0; i < n; ++i) {
getchar();
int A, B;
scanf("%d%d", &A, &B);
add_edge(i, t, A);
add_edge(s, i, B);
}
for (int i = 0; i < m; ++i) {
getchar();
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
add_edge(a - 1, b - 1, w);
add_edge(b - 1, a - 1, w);
}
printf("%d\n", max_flow(s, t)); return 0;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store