Pagini recente » Cod sursa (job #2009002) | Cod sursa (job #1251196) | Cod sursa (job #331244) | Cod sursa (job #2998545) | Cod sursa (job #867609)
Cod sursa(job #867609)
# include <cstdio>
# include <cstring>
# include <algorithm>
# include <queue>
using namespace std;
#define MAX_VERT 10005
#define MAX_ARC 5006
#define INF 0x3f3f3f3f
typedef int flowtype;
class MaxFlow{
int first, last, kol;
int beg[MAX_VERT], tbeg[MAX_VERT], dist[MAX_VERT];
struct Arc{
int s, prev;
flowtype cap;
} arc[MAX_ARC];
bool BFS(){
memcpy(tbeg, beg, sizeof beg);
memset(dist, -1, sizeof dist);
queue<int> Q;
Q.push(first);
dist[first] = 1;
for (int i; dist[last] == -1 && Q.size();){
i=Q.front();
Q.pop();
for (int j = beg[i]; j != -1; j=arc[j].prev){
if (dist[arc[j].s] == -1 && arc[j].cap > 0){
Q.push(arc[j].s);
dist[arc[j].s] = dist[i]+1;
}
}
}
return dist[last] != -1;
}
flowtype DFS(int x, flowtype mx_flow){
if (x == last || !mx_flow)
return mx_flow;
flowtype ret = 0, tec = 0;
for (int &i = tbeg[x]; i != -1; i = arc[i].prev){
if (dist[x]+1 == dist[arc[i].s] && arc[i].cap>0){
tec = DFS(arc[i].s, min(mx_flow, arc[i].cap));
arc[i].cap -= tec;
arc[i^1].cap += tec;
mx_flow -= tec;
ret += tec;
if (!mx_flow)
break;
}
}
return ret;
}
public:
MaxFlow(){
init();
}
void init(){
memset(beg, -1, sizeof beg);
kol = 0;
first = 0;
last = 0;
}
void set_last(int last){
this->last = last;
}
void set_first(int first){
this->first = first;
}
void add_arc(int f, int s, flowtype cap){
arc[kol].s = s;
arc[kol].prev = beg[f];
beg[f] = kol;
arc[kol++].cap = cap;
arc[kol].s = f;
arc[kol].prev = beg[s];
beg[s] = kol;
arc[kol++].cap = 0;
}
flowtype flow(){
flowtype ret = 0;
while (BFS())
ret += DFS(first, INF);
return ret;
}
} graph;
int main() {
freopen ("maxflow.in", "r", stdin);
freopen ("maxflow.out", "w", stdout);
int n, e, u, v, c, i;
scanf("%d%d", &n, &e);
graph.set_first (1), graph.set_last (n);
for(i=0; i<e; i++) {
scanf("%d%d%d", &u, &v, &c);
graph.add_arc (u, v, c);
}
printf("%d\n", graph.flow ());
return 0;
}