Pagini recente » Diferente pentru utilizator/mpatrascu intre reviziile 4 si 9 | Diferente pentru documentatie intre reviziile 97 si 109 | Cod sursa (job #2663253) | Borderou de evaluare (job #265526) | Cod sursa (job #1863208)
#include <iostream>
#include <fstream>
#define INF 0x3f3f3f3f
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n,m;
int rc[1001][1001];//c[i][j] - capacity of edge from i to j in the residual graph
int a[1001][1001];//adjacency list
int viz[1001];//viz[i] = 1 if i is visited, otherwise 0
int p[1001];//parent of vertex i in bfs (0 if i is the root)
int c[1001];//queue
int bfs(int s, int t){
int i,j,ke,ve,v;//
for(i = 1; i <= n; i++) viz[i] = 0;//vertices are not visited
ke = ve = 1;
c[ke] = s;//enqueue source
viz[s] = 1;//mark source as visited
while(ke <= ve){//while queue is not empty
v = c[ke];
ke = ke + 1;//dequeue
for(i = 1; i <= a[v][0];i++){
j = a[v][i];
if(rc[v][j] > 0 and viz[j] == 0){
ve = ve + 1;//enqueue j
c[ve] = j;
p[j] = v;
viz[j] = 1;//mark j as visited
}
}
}
if(viz[t] == 1) return 1;//if sink is reached return 1
else return 0;//else return 0
}
void maxflow(int s, int t){//s - source, t - sink
int flow, i, j;
int max_flow = 0; // There is no flow initially
// Augment the flow while there is path from source to sink
while(bfs(s,t)){
flow = INF;
//find the maximum flow through the path found.
i = t;
while(i != s){
flow = min(flow, rc[p[i]][i]);
i = p[i];
}
// update residual capacities of the edges and reverse edges along the path
i = t;
while(i != s){
rc[p[i]][i] -= flow;
rc[i][p[i]] += flow;
i = p[i];
}
max_flow = max_flow + flow;
}
out << max_flow;
}
int main()
{
int i,x,y,co;
in >> n >> m;//number of vertices and edges
for(i = 1; i <= m; i++){
in >> x >> y >> co;
rc[x][y] = co;
a[x][0]++;
a[x][a[x][0]] = y;
}
maxflow(1,n);
return 0;
}