Pagini recente » Cod sursa (job #446563) | Cod sursa (job #1092201) | Cod sursa (job #3221114) | Cod sursa (job #1724488) | Cod sursa (job #2841033)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
struct muchie
{
int y, flow, cap, rev;
};
struct Graph
{
vector<vector<muchie> > G;
vector<int> level, start;
Graph(int n)
{
G.resize(n + 1);
level.resize(n + 1);
start.resize(n + 1);
}
inline void AddEdge(int x, int y, int cap)
{
G[x].push_back({y, 0, cap, 1});
G[y].push_back({x, 0, 0, G[x].size() - 1});
}
inline bool BFS(int s, int t)
{
fill(level.begin(), level.end(), -1);
level[s] = 0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int nd = q.front();
q.pop();
for(auto it: G[nd])
if(level[it.y] == -1 && it.flow < it.cap)
{
level[it.y] = level[nd] + 1;
q.push(it.y);
}
}
return (level[t] == -1 ? 0 : 1);
}
inline int sendFlow(int s, int flow, int t){
if(s == t)
return flow;
for(; start[s] < G[s].size(); ++start[s]){
muchie &e = G[s][start[s]];
if(level[e.y] == level[s] + 1 && e.flow < e.cap){
int cur_flw = min(flow, e.cap - e.flow);
int temp_flow = sendFlow(e.y, cur_flw, t);
if(temp_flow > 0){
e.flow += temp_flow;
G[e.y][e.rev].flow -= temp_flow;
return temp_flow;
}
}
}
return 0;
}
inline int MaxFlow(int s, int t){
if(s == t)
return -1;
int rez = 0;
while(BFS(s, t)){
fill(start.begin(), start.end(), 0);
while(int flow = sendFlow(s, (1 << 30), t))
rez += flow;
}
return rez;
}
};
int main()
{
int n, m;
fin >> n >> m;
Graph G(n);
for(int i = 1; i <= m; ++i){
int x, y, cap;
fin >> x >> y >> cap;
G.AddEdge(x, y, cap);
}
fout << G.MaxFlow(1, n) << '\n';
return 0;
}