Pagini recente » Cod sursa (job #1152654) | Cod sursa (job #2957437) | Cod sursa (job #2716365) | Borderou de evaluare (job #2772026) | Cod sursa (job #768387)
Cod sursa(job #768387)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 1001
short N, GR[maxn][maxn], tree[maxn], queue[maxn];
int C[maxn][maxn], F[maxn][maxn], maxFlow;
void read(const char *file);
int BF(short source, short sink);
int main()
{
FILE *out;
short source, sink, i, j, node;
int flow;
read("maxflow.in");
source = 1;
sink = N;
while(BF(source, sink))
for(i = 1; i <= GR[sink][0]; ++i)
{
node = GR[sink][i];
if(node == source || C[node][sink] <= F[node][sink])
continue;
flow = C[node][sink] - F[node][sink];
for(j = node; j != source && j; j = tree[j])
if(flow > C[tree[j]][j] - F[tree[j]][j])
flow = C[tree[j]][j] - F[tree[j]][j];
if(flow == 0) continue;
F[node][sink] += flow;
F[sink][node] -= flow;
for(j = node; j != source && j; j = tree[j])
F[tree[j]][j] += flow,
F[j][tree[j]] -= flow;
maxFlow += flow;
}
out = fopen("maxflow.out", "w");
fprintf(out, "%d\n", maxFlow);
fclose(out);
return 0;
}
int BF(short source, short sink)
{
short l, r, node, next, i;
memset(tree, 0, sizeof(tree));
tree[source] = -1;
queue[0] = source;
for(l = r = 0; l <= r; ++l)
{
node = queue[l];
for(i = 1; i <= GR[node][0]; ++i)
{
next = GR[node][i];
if(!tree[next] && C[node][next] > F[node][next])
{
tree[next] = node;
queue[++r] = next;
}
}
}
return tree[sink];
}
void read(const char *file)
{
FILE *in = fopen(file, "r");
short m, a, b;
int c;
fscanf(in, "%hd %hd", &N, &m);
for(; m; --m)
{
fscanf(in, "%hd %hd %d", &a, &b, &c);
C[a][b] = c;
GR[a][ ++GR[a][0] ] = b;
GR[b][ ++GR[b][0] ] = a;
}
fclose(in);
}