Pagini recente » Borderou de evaluare (job #2017055) | Borderou de evaluare (job #2664604) | Cod sursa (job #1819442) | Cod sursa (job #2786963)
#include <iostream>
#include <climits>
#include <fstream>
#include <vector>
#include <queue>
#define VMAX 1000
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector <int> adj[VMAX];
int V, E, x, y;
int flow[VMAX][VMAX], capacity[VMAX][VMAX];
int parent[VMAX];
bool visited[VMAX];
bool BFS()
{
queue <int> q;
for (int i = 0; i < V; ++i) visited[i] = false;
q.push(0);
visited[0] = true;
parent[0] = -1;
while (!q.empty())
{
int u = q.front();
q.pop();
if (u == V - 1) continue;
for (auto w:adj[u])
if (visited[w] == false && flow[u][w] < capacity[u][w])
{
visited[w] = true;
parent[w] = u;
q.push(w);
}
}
return visited[V - 1];
}
int DFS()
{
int temp_flow, nod_crt, max_flow = 0;
for (auto w:adj[V - 1])
{
if (visited[w] == false || flow[w][V - 1] >= capacity[w][V - 1])
continue;
parent[V - 1] = w;
temp_flow = INT_MAX;
nod_crt = V - 1;
while (nod_crt)
{
temp_flow = min(temp_flow, capacity[parent[nod_crt]][nod_crt] - flow[parent[nod_crt]][nod_crt]);
nod_crt = parent[nod_crt];
}
nod_crt = V - 1;
while (nod_crt)
{
flow[parent[nod_crt]][nod_crt] += temp_flow;
flow[nod_crt][parent[nod_crt]] -= temp_flow;
nod_crt = parent[nod_crt];
}
max_flow += temp_flow;
}
return max_flow;
}
int main()
{
fin >> V >> E;
while (E--)
{
fin >> x >> y >> capacity[x - 1][y - 1];
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
int max_flow = 0;
while (BFS())
max_flow += DFS();
fout << max_flow;
fin.close();
fout.close();
return 0;
}