Pagini recente » Cod sursa (job #49812) | Cod sursa (job #327340) | Cod sursa (job #1885522) | Cod sursa (job #1155202) | Cod sursa (job #3155164)
#pragma GCC optimize("Ofast,unroll-loops")
#include <bits/stdc++.h>
#define sz(a) ((int)(a).size())
#define all(a) (a).begin(), (a).end()
#define fi first
#define se second
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;
}
};
#ifdef LOCAL
InParser fin("input.txt");
#define fout cout
#else
#define FILE_NAME "maxflow"
InParser fin(FILE_NAME ".in");
ofstream fout(FILE_NAME ".out");
#define endl '\n'
#endif
typedef long long ll;
typedef pair<int, int> pii;
const int NMAX = 1005;
const int INF = 2e9+5;
int n, m;
int g[NMAX][NMAX];
bool viz[NMAX];
int nxt[NMAX];
void read() {
fin >> n >> m;
for (int i = 1, x, y, c; i <= m; i++) {
fin >> x >> y >> c;
g[x][y] = c;
}
}
bool dfs(int x) {
if (x == n) return 1;
viz[x] = true;
for (int i = 1; i <= n; i++) {
if (g[x][i] > 0 && !viz[i]) {
nxt[x] = i;
int ret = dfs(i);
if (ret) return 1;
}
}
return 0;
}
bool bfs() {
memset(viz, 0, n + 1);
queue<int> q;
q.push(1);
viz[1] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 1; i <= n; i++) {
if (!viz[i] && g[u][i] > 0) {
nxt[i] = u;
viz[i] = true;
q.push(i);
}
}
}
return viz[n];
}
int solve() {
int max_flow = 0;
while (bfs()) {
int flow = INF;
for (int v = n; v != 1; v = nxt[v])
flow = min(flow, g[nxt[v]][v]);
for (int v = n; v != 1; v = nxt[v]) {
g[nxt[v]][v] -= flow;
g[v][nxt[v]] += flow;
}
max_flow += flow;
}
return max_flow;
}
signed main() {
read();
fout << solve() << endl;
return 0;
}