Friday, June 2, 2006

Maximum Flow

Time Complexity: O(n*m^2)
Ford Fulkerson Algorithm




const int maxn = 201; //maxn = maxn plus one!
const int maxint = 0x7fffffff;
struct Node {
int l, //label
p; //check
};
struct Arc {
int c, //capacity
f; //flow
};

Node lt[maxn]; //extendable path
Arc g[maxn][maxn]; //direct, range 1 to n
int n;
int s,t; //source, terminal

int check() { //return a labeled but unchecked vertex
int i = 1;
while(i<=n && (lt[i].l==0 || lt[i].p!=0)) i++;
return (i>n ? 0 : i);
}

//return true if no extendable path exists,
//or false and improving variable a;
bool ford(int &a) {
int i,j,m,x;
memset(lt,0,(n+1)*sizeof(Node));
lt[s].l = s;
do {
i = check();
if(i==0)
return true;
for(j=1;j<=n;j++) {
//unlabeled vertexes connected with i
if(lt[j].l==0 && (g[i][j].c!=0 || g[j][i].c!=0)) {
if(g[i][j].f lt[j].l = i;
if(g[j][i].f>0)
lt[j].l = -i;
}
}
lt[i].p = 1;
}while(lt[t].l==0);
m = t; a = maxint;
do{
j = m; m = abs(lt[j].l);
if(lt[j].l<0)
x = g[j][m].f - 0;
if(lt[j].l>0)
x = g[m][j].c - g[m][j].f;
if(a>x)
a = x;
}while(m!=s);
return false;
}

void fulkerson(int a) {
int m,j;
m = t;
do {
j = m; m = abs(lt[j].l);
if(lt[j].l<0)
g[j][m].f = g[j][m].f - a;
if(lt[j].l>0)
g[m][j].f = g[m][j].f + a;
}while(m!=s);
}

void max_flow() {
//s = 1; t = n; //set source and terminal
int del = 0;
while(!ford(del)) {
fulkerson(del);
}
}

No comments:

Post a Comment

Please post your comment here. ;)