Pagini recente » Cod sursa (job #3280602) | Profil lolismek | Istoria paginii asociatia-infoarena | Cod sursa (job #3249668) | Cod sursa (job #2773878)
#include <bits/stdc++.h>
using namespace std;
class MaxFlowSolver{
int source;
int destination;
struct edge_t{
int u,v;
long long cap,flow;
};
vector<edge_t> edges;
vector<vector<int> > graph;
vector<int> viz;
vector<int> father;
queue<int> q;
bool bfs(int source,int destination){
for(auto &it:viz){
it = 0;
}
for(auto &it:father){
it = 0;
}
while(q.empty() == false){
q.pop();
}
viz[source] = 1;
q.push(source);
while(!q.empty()){
int nod = q.front();
q.pop();
if(nod == destination){
continue;
}
for(auto it:graph[nod]){
if(edges[it].flow < edges[it].cap && viz[edges[it].v] == false){
viz[edges[it].v] = 1;
father[edges[it].v] = it;
q.push(edges[it].v);
}
}
}
return viz[destination];
}
public:
MaxFlowSolver(int n){
edges.clear();
graph = vector<vector<int> >(n + 2,vector<int>(0,0));
source = 1;
destination = n;
q = queue<int>();
father = vector<int>(n + 2,0);
viz = vector<int>(n + 2,0);
}
void addEdge(int x,int y,long long cap){
edges.push_back({x,y,cap,0});
edges.push_back({y,x,0,0});
graph[x].push_back((int)edges.size() - 2);
graph[y].push_back((int)edges.size() - 1);
}
long long getMaxFlow(){
long long maxflow = 0;
while(bfs(source,destination)){
for(auto it:graph[destination]){
if(viz[edges[it ^ 1].u] && edges[it ^ 1].flow < edges[it ^ 1].cap){
father[destination] = it ^ 1;
long long fmin = 1e18;
for(int nod = destination;nod != source;nod = edges[father[nod]].u){
fmin = min(edges[father[nod]].cap - edges[father[nod]].flow,fmin);
}
maxflow += fmin;
for(int nod = destination;nod != source;nod = edges[father[nod]].u){
edges[father[nod]].flow += fmin;
edges[father[nod] ^ 1].flow -= fmin;
}
}
}
}
return maxflow;
}
};
int main(){
FILE *f = fopen("maxflow.in","r");
FILE *g = fopen("maxflow.out","w");
int n,m;
fscanf(f,"%d %d",&n,&m);
MaxFlowSolver solver(n);
for(int i = 1;i <= m;i++){
int u,v,w;
fscanf(f,"%d %d %d",&u,&v,&w);
solver.addEdge(u,v,w);
}
fprintf(g,"%lld\n",solver.getMaxFlow());
fclose(f);
fclose(g);
return 0;
}