Pagini recente » Cod sursa (job #3276123) | Cod sursa (job #2583996) | Cod sursa (job #1861963) | Cod sursa (job #2916251) | Cod sursa (job #2784200)
#include <bits/stdc++.h>
using namespace std;
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
ofstream out("maxflow.out");
const int MAXN = 1e3;
const int MAXM = 5e3;
struct Edge {
int next;
int capacity;
int flow;
int rev;
Edge(int _next, int _capacity, int _flow, int _rev) {
next = _next;
capacity = _capacity;
flow = _flow;
rev = _rev;
}
};
int n, m;
vector< Edge > g[MAXN + 2];
int depth[MAXN + 2];
bool bfs() {
queue<int> q;
memset(depth, 0, sizeof(depth));
depth[1] = 1;
bool reachedSink = false;
q.push(1);
int cur;
while (q.size()) {
cur = q.front();
q.pop();
for (auto &x : g[cur]) {
if (x.next == n)
reachedSink = true;
if (depth[x.next] == 0 && x.capacity - x.flow > 0) {
depth[x.next] = depth[cur] + 1;
q.push(x.next);
}
}
}
return reachedSink;
}
int dfs(int cur, int flow) {
if (cur == n)
return flow;
for (auto &x : g[cur]) {
if (depth[x.next] == depth[cur] + 1 && x.capacity - x.flow > 0) {
int tmpFlow = dfs(x.next, min(flow, x.capacity - x.flow));
if (tmpFlow > 0) {
x.flow += tmpFlow;
g[x.next][x.rev].flow -= tmpFlow;
return tmpFlow;
}
}
}
depth[cur] = -1;
return 0;
}
int main() {
InParser in("maxflow.in");
in >> n >> m;
for (int i = 0; i < m; ++ i) {
int x, y, z;
in >> x >> y >> z;
g[x].push_back(Edge(y, z, 0, g[y].size()));
g[y].push_back(Edge(x, 0, 0, g[x].size() - 1));
}
int maxFlow = 0;
while (bfs()) {
int tmpFlow = 0;
do {
tmpFlow = dfs(1, 2e9);
maxFlow += tmpFlow;
} while (tmpFlow > 0);
}
out << maxFlow << '\n';
return 0;
}