Pagini recente » Cod sursa (job #3039340) | Cod sursa (job #332911) | Cod sursa (job #2346548) | Cod sursa (job #3134595) | Cod sursa (job #3298375)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
const int INF = 1e9;
using pii = pair<int, int>;
int n, m;
struct DINIC
{
struct Edge
{
int u, v, c;
};
vector<Edge> e;
vector<int> adj[MAXN];
bool visited[MAXN];
int depth[MAXN];
void add_edge(int u, int v, int c)
{
adj[u].push_back(e.size());
e.push_back({u, v, c});
adj[v].push_back(e.size());
e.push_back({v, u, -c});
}
int t1;
int flow(int u, int d)
{
if(d <= 0)
return 0;
if(u == t1)
return max(d, 0);
for(int v0 : adj[u])
{
int newd;
if(depth[e[v0].v] == depth[u] + 1 && (newd = flow(e[v0].v, min(d, e[v0].c))))
{
e[v0].c -= newd;
e[v0 ^ 1].c += newd;
return newd;
}
}
return 0;
}
bool canbfs(int s, int t)
{
for(int i = 1; i <= n; i++)
visited[i] = false;
queue<int> q;
q.push(s);
visited[s] = true;
while(!q.empty())
{
int u = q.front();
q.pop();
for(int v0 : adj[u])
{
int v = e[v0].v;
if(visited[v] || e[v0].c == 0)
continue;
visited[v] = true;
depth[v] = depth[u] + 1;
q.push(v);
}
}
return visited[t];
}
int dinic(int s, int t)
{
t1 = t;
int ans = 0;
while(canbfs(s, t))
{
ans += flow(s, INF);
}
return ans;
}
};
DINIC dinic;
int32_t main()
{
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int u, v, c;
cin >> u >> v >> c;
dinic.add_edge(u, v, c);
}
cout << dinic.dinic(1, n);
return 0;
}