Pagini recente » Borderou de evaluare (job #1924897) | Info Oltenia 2019 Proba Individuala Clasele 11-12 | Rezultate Info Oltenia 2019 Proba Individuala | Cod sursa (job #1351110) | Cod sursa (job #2888243)
#include <bits/stdc++.h>
using namespace std;
class Graph{
public:
const int N;
vector<vector<int>> neighbors;
vector<vector<int>> capacity;
public:
Graph(const int& N): N(N){
neighbors.resize(N);
capacity.assign(N, vector<int>(N));
}
void addEdge(int x, int y, int c){
neighbors[x].push_back(y);
neighbors[y].push_back(x);
capacity[x][y] = c;
}
};
class Dinic{
private:
const Graph& G;
const int N;
const int SRC;
const int DEST;
const int INF = 1e8;
vector<vector<int>> f;
vector<int> dist;
vector<int> startEdgeIdx;
int bfs(){
fill(dist.begin(), dist.end(), INF);
queue<int> q;
q.push(SRC);
dist[SRC] = 0;
while(!q.empty()){
int node = q.front();
q.pop();
if(dist[node] == dist[DEST]){
break;
}
for(int nextNode: G.neighbors[node]){
int remainingCapacity = G.capacity[node][nextNode] - f[node][nextNode];
if(remainingCapacity > 0 && dist[nextNode] == INF){
dist[nextNode] = 1 + dist[node];
q.push(nextNode);
}
}
}
return (dist[DEST] != INF);
}
int dfs(int node, int minDelta){
if(node == DEST){
return minDelta;
}
for(; startEdgeIdx[node] < (int)G.neighbors[node].size(); ++startEdgeIdx[node]){
int nextNode = G.neighbors[node][startEdgeIdx[node]];
int remainingCapacity = G.capacity[node][nextNode] - f[node][nextNode];
if(remainingCapacity > 0 && dist[node] + 1 == dist[nextNode]){
int delta = dfs(nextNode, min(minDelta, remainingCapacity));
if(delta > 0){
f[node][nextNode] += delta;
f[nextNode][node] -= delta;
return delta;
}
}
}
return 0;
}
public:
Dinic(const Graph& G, const int& SRC, const int& DEST):
G(G), N(G.N), SRC(SRC), DEST(DEST){
}
int computeMaxFlow(){
f.assign(N, vector<int>(N, 0));
dist.resize(N);
startEdgeIdx.resize(N);
int maxFlow = 0;
while(bfs()){
fill(startEdgeIdx.begin(), startEdgeIdx.end(), 0);
int delta = INF;
while(delta > 0){
delta = dfs(SRC, INF);
maxFlow += delta;
}
}
return maxFlow;
}
};
int main(){
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
int N, M;
cin >> N >> M;
Graph G(N);
int x, y, c;
for(int i = 0; i < M; ++i){
cin >> x >> y >> c;
G.addEdge(x - 1, y - 1, c);
}
cout << Dinic(G, 0, N - 1).computeMaxFlow();
cin.close();
cout.close();
return 0;
}